forked from chipsalliance/verible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbol_table.cc
1981 lines (1766 loc) · 76.8 KB
/
symbol_table.cc
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 2017-2020 The Verible Authors.
//
// 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 "verilog/analysis/symbol_table.h"
#include <iostream>
#include <sstream>
#include <stack>
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "common/strings/display_utils.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/token_info.h"
#include "common/text/tree_context_visitor.h"
#include "common/text/tree_utils.h"
#include "common/text/visitors.h"
#include "common/util/enum_flags.h"
#include "common/util/logging.h"
#include "common/util/spacer.h"
#include "common/util/value_saver.h"
#include "verilog/CST/class.h"
#include "verilog/CST/declaration.h"
#include "verilog/CST/functions.h"
#include "verilog/CST/macro.h"
#include "verilog/CST/module.h"
#include "verilog/CST/net.h"
#include "verilog/CST/package.h"
#include "verilog/CST/parameters.h"
#include "verilog/CST/port.h"
#include "verilog/CST/seq_block.h"
#include "verilog/CST/statement.h"
#include "verilog/CST/tasks.h"
#include "verilog/CST/type.h"
#include "verilog/CST/verilog_nonterminals.h"
#include "verilog/analysis/verilog_project.h"
#include "verilog/parser/verilog_parser.h"
#include "verilog/parser/verilog_token_enum.h"
namespace verilog {
using verible::AutoTruncate;
using verible::StringSpanOfSymbol;
using verible::SyntaxTreeLeaf;
using verible::SyntaxTreeNode;
using verible::TokenInfo;
using verible::TreeContextVisitor;
using verible::ValueSaver;
// Returns string_view of `text` with outermost double-quotes removed.
// If `text` is not wrapped in quotes, return it as-is.
static absl::string_view StripOuterQuotes(absl::string_view text) {
return absl::StripSuffix(absl::StripPrefix(text, "\""), "\"");
}
static const verible::EnumNameMap<SymbolMetaType>& SymbolMetaTypeNames() {
static const verible::EnumNameMap<SymbolMetaType> kSymbolMetaTypeNames({
// short-hand annotation for identifier reference type
{"<root>", SymbolMetaType::kRoot},
{"class", SymbolMetaType::kClass},
{"module", SymbolMetaType::kModule},
{"package", SymbolMetaType::kPackage},
{"parameter", SymbolMetaType::kParameter},
{"typedef", SymbolMetaType::kTypeAlias},
{"data/net/var/instance", SymbolMetaType::kDataNetVariableInstance},
{"function", SymbolMetaType::kFunction},
{"task", SymbolMetaType::kTask},
{"struct", SymbolMetaType::kStruct},
{"enum", SymbolMetaType::kEnumType},
{"<enum constant>", SymbolMetaType::kEnumConstant},
{"interface", SymbolMetaType::kInterface},
{"<unspecified>", SymbolMetaType::kUnspecified},
{"<callable>", SymbolMetaType::kCallable},
});
return kSymbolMetaTypeNames;
}
std::ostream& operator<<(std::ostream& stream, SymbolMetaType symbol_type) {
return SymbolMetaTypeNames().Unparse(symbol_type, stream);
}
static absl::string_view SymbolMetaTypeAsString(SymbolMetaType type) {
return SymbolMetaTypeNames().EnumName(type);
}
// Root SymbolTableNode has no key, but we identify it as "$root"
static constexpr absl::string_view kRoot("$root");
std::ostream& SymbolTableNodeFullPath(std::ostream& stream,
const SymbolTableNode& node) {
if (node.Parent() != nullptr) {
SymbolTableNodeFullPath(stream, *node.Parent()) << "::" << *node.Key();
} else {
stream << kRoot;
}
return stream;
}
static std::string ContextFullPath(const SymbolTableNode& context) {
std::ostringstream stream;
SymbolTableNodeFullPath(stream, context);
return stream.str();
}
std::ostream& ReferenceNodeFullPath(std::ostream& stream,
const ReferenceComponentNode& node) {
if (node.Parent() != nullptr) {
ReferenceNodeFullPath(stream, *node.Parent()); // recursive
}
return node.Value().PrintPathComponent(stream);
}
static std::string ReferenceNodeFullPathString(
const ReferenceComponentNode& node) {
std::ostringstream stream;
ReferenceNodeFullPath(stream, node);
return stream.str();
}
static std::ostream& operator<<(std::ostream& stream,
const ReferenceComponentNode& ref_node) {
ref_node.PrintTree(
&stream,
[](std::ostream& s, const ReferenceComponent& ref_comp) -> std::ostream& {
return s << ref_comp;
});
return stream;
}
// Validates iterator/pointer stability when calling VectorTree::NewChild.
// Detects unwanted reallocation.
static ReferenceComponentNode* CheckedNewChildReferenceNode(
ReferenceComponentNode* parent, const ReferenceComponent& component) {
const auto& siblings(parent->Children());
if (!siblings.empty()) {
CHECK_LT(siblings.size(), siblings.capacity())
<< "\nReallocation would invalidate pointers to reference nodes at:\n"
<< *parent << "\nFix: pre-allocate child nodes.";
}
// Otherwise, this first node had no prior siblings, so no need to check.
return parent->NewChild(component); // copy
}
static absl::Status DiagnoseMemberSymbolResolutionFailure(
absl::string_view name, const SymbolTableNode& context) {
const absl::string_view context_name =
context.Parent() == nullptr ? kRoot : *context.Key();
return absl::NotFoundError(
absl::StrCat("No member symbol \"", name, "\" in parent scope (",
SymbolMetaTypeAsString(context.Value().metatype), ") ",
context_name, "."));
}
static const SymbolTableNode* LookupSymbolUpwards(
const SymbolTableNode& context, absl::string_view symbol);
class SymbolTable::Builder : public TreeContextVisitor {
public:
Builder(const VerilogSourceFile& source, SymbolTable* symbol_table,
VerilogProject* project)
: source_(&source),
token_context_(MakeTokenContext()),
symbol_table_(symbol_table),
current_scope_(&symbol_table_->MutableRoot()) {}
std::vector<absl::Status> TakeDiagnostics() {
return std::move(diagnostics_);
}
private: // methods
void Visit(const SyntaxTreeNode& node) final {
const auto tag = static_cast<NodeEnum>(node.Tag().tag);
VLOG(1) << __FUNCTION__ << " [node]: " << tag;
switch (tag) {
case NodeEnum::kModuleDeclaration:
DeclareModule(node);
break;
case NodeEnum::kGenerateIfClause:
DeclareGenerateIf(node);
break;
case NodeEnum::kGenerateElseClause:
DeclareGenerateElse(node);
break;
case NodeEnum::kPackageDeclaration:
DeclarePackage(node);
break;
case NodeEnum::kClassDeclaration:
DeclareClass(node);
break;
case NodeEnum::kFunctionPrototype: // fall-through
case NodeEnum::kFunctionDeclaration:
DeclareFunction(node);
break;
case NodeEnum::kFunctionHeader:
SetupFunctionHeader(node);
break;
case NodeEnum::kTaskPrototype: // fall-through
case NodeEnum::kTaskDeclaration:
DeclareTask(node);
break;
// No special handling needed for kTaskHeader
case NodeEnum::kPortList:
DeclarePorts(node);
break;
case NodeEnum::kPortItem: // fall-through
// for function/task parameters
case NodeEnum::kPortDeclaration: // fall-through
case NodeEnum::kNetDeclaration: // fall-through
case NodeEnum::kStructUnionMember: // fall-through
case NodeEnum::kTypeDeclaration: // fall-through
case NodeEnum::kDataDeclaration:
DeclareData(node);
break;
case NodeEnum::kParamDeclaration:
DeclareParameter(node);
break;
case NodeEnum::kTypeInfo: // fall-through
case NodeEnum::kDataType:
DescendDataType(node);
break;
case NodeEnum::kReferenceCallBase:
DescendReferenceExpression(node);
break;
case NodeEnum::kActualParameterList:
DescendActualParameterList(node);
break;
case NodeEnum::kPortActualList:
DescendPortActualList(node);
break;
case NodeEnum::kGateInstanceRegisterVariableList: {
// TODO: reserve() to guarantee pointer/iterator stability in VectorTree
Descend(node);
break;
}
case NodeEnum::kNetVariable:
DeclareNet(node);
break;
case NodeEnum::kRegisterVariable:
DeclareRegister(node);
break;
case NodeEnum::kGateInstance:
DeclareInstance(node);
break;
case NodeEnum::kVariableDeclarationAssignment:
DeclareVariable(node);
break;
case NodeEnum::kQualifiedId:
HandleQualifiedId(node);
break;
case NodeEnum::kPreprocessorInclude:
EnterIncludeFile(node);
break;
case NodeEnum::kExtendsList:
DescendExtends(node);
break;
case NodeEnum::kStructType:
DescendStructType(node);
break;
case NodeEnum::kEnumType:
DescendEnumType(node);
break;
case NodeEnum::kLPValue:
HandlePossibleImplicitDeclaration(node);
break;
default:
Descend(node);
break;
}
VLOG(1) << "end of " << __FUNCTION__ << " [node]: " << tag;
}
// This overload enters 'scope' for the duration of the call.
// New declared symbols will belong to that scope.
void Descend(const SyntaxTreeNode& node, SymbolTableNode* scope) {
const ValueSaver<SymbolTableNode*> save_scope(¤t_scope_, scope);
Descend(node);
}
void Descend(const SyntaxTreeNode& node) {
TreeContextVisitor::Visit(node); // maintains syntax tree Context() stack.
}
// RAII-class balance the Builder::references_builders_ stack.
// The work of moving collecting references into the current scope is done in
// the destructor.
class CaptureDependentReference {
public:
explicit CaptureDependentReference(Builder* builder)
: builder_(builder),
saved_branch_point_(builder_->reference_branch_point_) {
// Push stack space to capture references.
builder_->reference_builders_.emplace(/* DependentReferences */);
// Reset the branch point to start new named parameter/port chains
// from the same context.
builder_->reference_branch_point_ = nullptr;
}
~CaptureDependentReference() {
// This completes the capture of a chain of dependent references.
// Ref() can be empty if the subtree doesn't reference any identifiers.
// Empty refs are non-actionable and must be excluded.
DependentReferences& ref(Ref());
if (!ref.Empty()) {
builder_->current_scope_->Value().local_references_to_bind.emplace_back(
std::move(ref));
}
builder_->reference_builders_.pop();
builder_->reference_branch_point_ = saved_branch_point_; // restore
}
// Returns the chain of dependent references that were built.
DependentReferences& Ref() const {
return builder_->reference_builders_.top();
}
private:
Builder* builder_;
ReferenceComponentNode* saved_branch_point_;
};
void DescendReferenceExpression(const SyntaxTreeNode& reference) {
// capture expressions referenced from the current scope
const CaptureDependentReference capture(this);
// subexpressions' references will be collected before this one
Descend(reference); // no scope change
}
void DescendExtends(const SyntaxTreeNode& extends) {
VLOG(2) << __FUNCTION__ << " from: " << CurrentScopeFullPath();
{
// At this point we are already inside the scope of the class declaration,
// however, the base classes should be resolved starting from the scope
// that *contains* this class declaration.
const ValueSaver<SymbolTableNode*> save(¤t_scope_,
current_scope_->Parent());
// capture the one base class type referenced by 'extends'
const CaptureDependentReference capture(this);
Descend(extends);
}
// Link this new type reference as the base type of the current class being
// declared.
const DependentReferences& recent_ref =
current_scope_->Parent()->Value().local_references_to_bind.back();
const ReferenceComponentNode* base_type_ref =
recent_ref.LastTypeComponent();
SymbolInfo& current_declared_class_info = current_scope_->Value();
current_declared_class_info.parent_type.user_defined_type = base_type_ref;
}
// Traverse a subtree for a data type and collects type references
// originating from the current context.
// If the context is such that this type is used in a declaration,
// then capture that type information to be used later.
//
// The state/stack management here is intended to accommodate type references
// of arbitrary complexity.
// A generalized type could look like:
// "A#(.B(1))::C#(.D(E#(.F(0))))::G"
// This should produce the following reference trees:
// A -+- ::B
// |
// \- ::C -+- ::D
// |
// \- ::G
// E -+- ::F
//
void DescendDataType(const SyntaxTreeNode& data_type_node) {
VLOG(1) << __FUNCTION__ << ": " << StringSpanOfSymbol(data_type_node);
const CaptureDependentReference capture(this);
{
// Inform that named parameter identifiers will yield parallel children
// from this reference branch point. Start this out as nullptr, and set
// it once an unqualified identifier is encountered that starts a
// reference tree.
const ValueSaver<ReferenceComponentNode*> set_branch(
&reference_branch_point_, nullptr);
Descend(data_type_node);
// declaration_type_info_ will be restored after this closes.
}
if (declaration_type_info_ != nullptr) {
// 'declaration_type_info_' holds the declared type we want to capture.
if (verible::GetLeftmostLeaf(data_type_node) != nullptr) {
declaration_type_info_->syntax_origin = &data_type_node;
// Otherwise, if the type subtree contains no leaves (e.g. implicit or
// void), then do not assign a syntax origin.
}
const DependentReferences& type_ref(capture.Ref());
if (!type_ref.Empty()) {
// then some user-defined type was referenced
declaration_type_info_->user_defined_type =
type_ref.LastTypeComponent();
}
VLOG(2) << "declared type: " << *declaration_type_info_;
}
// In all cases, a type is being referenced from the current scope, so add
// it to the list of references to resolve (done by 'capture').
VLOG(1) << "end of " << __FUNCTION__;
}
void DescendActualParameterList(const SyntaxTreeNode& node) {
if (reference_branch_point_ != nullptr) {
// Pre-allocate siblings to guarantee pointer/iterator stability.
// FindAll* will also catch actual port connections inside preprocessing
// conditionals.
const size_t num_params = FindAllNamedParams(node).size();
// +1 to accommodate the slot needed for a nested type reference
// e.g. for "B" in "A#(.X(), .Y(), ...)::B"
reference_branch_point_->Children().reserve(num_params + 1);
}
Descend(node);
}
void DescendPortActualList(const SyntaxTreeNode& node) {
if (reference_branch_point_ != nullptr) {
// Pre-allocate siblings to guarantee pointer/iterator stability.
// FindAll* will also catch actual port connections inside preprocessing
// conditionals.
const size_t num_ports = FindAllActualNamedPort(node).size();
reference_branch_point_->Children().reserve(num_ports);
}
Descend(node);
}
void DescendStructType(const SyntaxTreeNode& struct_type) {
CHECK(struct_type.MatchesTag(NodeEnum::kStructType));
// Structs do not inherently have names, so they are all anonymous.
// Type declarations (typedefs) create named alias elsewhere.
const absl::string_view anon_name =
current_scope_->Value().CreateAnonymousScope("struct");
SymbolTableNode* new_struct = DeclareScopedElementAndDescend(
struct_type, anon_name, SymbolMetaType::kStruct);
// Create a self-reference to this struct type so that it can be linked
// for declarations that use this type.
const ReferenceComponent anon_type_ref{
.identifier = anon_name,
.ref_type = ReferenceType::kImmediate,
.required_metatype = SymbolMetaType::kStruct,
// pre-resolve this symbol immediately
.resolved_symbol = new_struct,
};
const CaptureDependentReference capture(this);
capture.Ref().PushReferenceComponent(anon_type_ref);
if (declaration_type_info_ != nullptr) {
declaration_type_info_->user_defined_type = capture.Ref().LastLeaf();
}
}
void DescendEnumType(const SyntaxTreeNode& enum_type) {
CHECK(enum_type.MatchesTag(NodeEnum::kEnumType));
const absl::string_view anon_name =
current_scope_->Value().CreateAnonymousScope("enum");
SymbolTableNode* new_enum = DeclareScopedElementAndDescend(
enum_type, anon_name, SymbolMetaType::kEnumType);
const ReferenceComponent anon_type_ref{
.identifier = anon_name,
.ref_type = ReferenceType::kImmediate,
.required_metatype = SymbolMetaType::kEnumType,
// pre-resolve this symbol immediately
.resolved_symbol = new_enum,
};
const CaptureDependentReference capture(this);
capture.Ref().PushReferenceComponent(anon_type_ref);
if (declaration_type_info_ != nullptr) {
declaration_type_info_->user_defined_type = capture.Ref().LastLeaf();
}
// Iterate over enumeration constants
for (const auto& itr : *new_enum) {
const auto enum_constant_name = itr.first;
const auto& symbol = itr.second;
const auto& syntax_origin =
*ABSL_DIE_IF_NULL(symbol.Value().syntax_origin);
const ReferenceComponent itr_ref{
.identifier = enum_constant_name,
.ref_type = ReferenceType::kImmediate,
.required_metatype = SymbolMetaType::kEnumConstant,
// pre-resolve this symbol immediately
.resolved_symbol = &symbol,
};
// CaptureDependentReference class doesn't support
// copy constructor
const CaptureDependentReference cap(this);
cap.Ref().PushReferenceComponent(anon_type_ref);
cap.Ref().PushReferenceComponent(itr_ref);
// Create default DeclarationTypeInfo
DeclarationTypeInfo decl_type_info;
const ValueSaver<DeclarationTypeInfo*> save_type(&declaration_type_info_,
&decl_type_info);
declaration_type_info_->syntax_origin = &syntax_origin;
declaration_type_info_->user_defined_type = cap.Ref().LastLeaf();
// Constants should be visible in current scope so we create
// variable instances with references to enum constants
//
// Consider using something different than kTypeAlias here
// (which is technically an alias for a type and not for a data/variable)
// e.g. kConstantAlias or even kGenericAlias.
EmplaceTypedElementInCurrentScope(syntax_origin, enum_constant_name,
SymbolMetaType::kTypeAlias);
}
}
void HandlePossibleImplicitDeclaration(const SyntaxTreeNode& node) {
VLOG(2) << __FUNCTION__;
// Only left-hand side of continuous assignment statements are allowed to
// implicitly declare nets (LRM 6.10: Implicit declarations).
if (Context().DirectParentsAre(
{NodeEnum::kNetVariableAssignment, NodeEnum::kAssignmentList,
NodeEnum::kContinuousAssignmentStatement})) {
CHECK(node.MatchesTag(NodeEnum::kLPValue));
DeclarationTypeInfo decl_type_info;
const ValueSaver<DeclarationTypeInfo*> save_type(&declaration_type_info_,
&decl_type_info);
declaration_type_info_->implicit = true;
Descend(node);
} else {
Descend(node);
}
}
void HandleIdentifier(const SyntaxTreeLeaf& leaf) {
const absl::string_view text = leaf.get().text();
VLOG(2) << __FUNCTION__ << ": " << text;
VLOG(2) << "current context: " << CurrentScopeFullPath();
if (Context().DirectParentIs(NodeEnum::kParamType)) {
// This identifier declares a value parameter.
EmplaceTypedElementInCurrentScope(leaf, text, SymbolMetaType::kParameter);
return;
}
if (Context().DirectParentIs(NodeEnum::kTypeAssignment)) {
// This identifier declares a type parameter.
EmplaceElementInCurrentScope(leaf, text, SymbolMetaType::kParameter);
return;
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kPortDeclaration}) ||
Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId,
NodeEnum::kDataTypeImplicitBasicIdDimensions,
NodeEnum::kPortItem})) {
// This identifier declares a (non-parameter) port (of a module,
// function, task).
EmplaceTypedElementInCurrentScope(
leaf, text, SymbolMetaType::kDataNetVariableInstance);
// TODO(fangism): Add attributes to distinguish public ports from
// private internals members.
return;
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kFunctionHeader})) {
// We deferred adding a declared function to the current scope until this
// point (from DeclareFunction()).
// Note that this excludes the out-of-line definition case,
// which is handled in DescendThroughOutOfLineDefinition().
const SyntaxTreeNode* decl_syntax =
Context().NearestParentMatching([](const SyntaxTreeNode& node) {
return node.MatchesTagAnyOf(
{NodeEnum::kFunctionDeclaration, NodeEnum::kFunctionPrototype});
});
if (decl_syntax == nullptr) return;
SymbolTableNode* declared_function = &EmplaceTypedElementInCurrentScope(
*decl_syntax, text, SymbolMetaType::kFunction);
// After this point, we've registered the new function with its return
// type, so we can switch context over to the newly declared function
// for its port interface and definition internals.
current_scope_ = declared_function;
return;
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kTaskHeader})) {
// We deferred adding a declared task to the current scope until this
// point (from DeclareFunction()).
// Note that this excludes the out-of-line definition case,
// which is handled in DescendThroughOutOfLineDefinition().
const SyntaxTreeNode* decl_syntax =
Context().NearestParentMatching([](const SyntaxTreeNode& node) {
return node.MatchesTagAnyOf(
{NodeEnum::kTaskDeclaration, NodeEnum::kTaskPrototype});
});
if (decl_syntax == nullptr) return;
SymbolTableNode* declared_task = EmplaceElementInCurrentScope(
*decl_syntax, text, SymbolMetaType::kTask);
// After this point, we've registered the new task,
// so we can switch context over to the newly declared function
// for its port interface and definition internals.
current_scope_ = declared_task;
return;
}
if (Context().DirectParentsAre({NodeEnum::kDataTypeImplicitIdDimensions,
NodeEnum::kStructUnionMember})) {
// This is a struct/union member. Add it to the enclosing scope.
// e.g. "foo" in "struct { int foo; }"
EmplaceTypedElementInCurrentScope(
leaf, text, SymbolMetaType::kDataNetVariableInstance);
return;
}
if (Context().DirectParentsAre(
{NodeEnum::kVariableDeclarationAssignment,
NodeEnum::kVariableDeclarationAssignmentList,
NodeEnum::kStructUnionMember})) {
// This is part of a declaration covered by kVariableDeclarationAssignment
// already, so do not interpret this as a reference.
// e.g. "z" in "struct { int y, z; }"
return;
}
if (Context().DirectParentsAre(
{NodeEnum::kEnumName, NodeEnum::kEnumNameList})) {
EmplaceTypedElementInCurrentScope(leaf, text,
SymbolMetaType::kEnumConstant);
return;
}
// In DeclareInstance(), we already planted a self-reference that is
// resolved to the instance being declared.
if (Context().DirectParentIs(NodeEnum::kGateInstance)) return;
if (Context().DirectParentIs(NodeEnum::kTypeDeclaration)) {
// This identifier declares a type alias (typedef).
EmplaceTypedElementInCurrentScope(leaf, text, SymbolMetaType::kTypeAlias);
return;
}
// Capture only referencing identifiers, omit declarative identifiers.
// This is set up when traversing references, e.g. types, expressions.
// All of the code below takes effect inside a CaptureDependentReferences
// RAII block.
if (reference_builders_.empty()) return;
// Building a reference, possible part of a chain or qualified
// reference.
DependentReferences& ref(reference_builders_.top());
const ReferenceComponent new_ref{
.identifier = text,
.ref_type = InferReferenceType(),
.required_metatype = InferMetaType(),
};
// For instances' named ports, and types' named parameters,
// add references as siblings of the same parent.
// (Recall that instances form self-references).
if (Context().DirectParentIsOneOf(
{NodeEnum::kActualNamedPort, NodeEnum::kParamByName})) {
CheckedNewChildReferenceNode(ABSL_DIE_IF_NULL(reference_branch_point_),
new_ref);
return;
}
// Handle possible implicit declarations here
if (declaration_type_info_ != nullptr && declaration_type_info_->implicit) {
const SymbolTableNode* resolved =
LookupSymbolUpwards(*ABSL_DIE_IF_NULL(current_scope_), text);
if (resolved == nullptr) {
// No explicit declaration found, declare here
SymbolTableNode& implicit_declaration =
EmplaceTypedElementInCurrentScope(
leaf, text, SymbolMetaType::kDataNetVariableInstance);
const ReferenceComponent implicit_ref{
.identifier = text,
.ref_type = InferReferenceType(),
.required_metatype = InferMetaType(),
// pre-resolve
.resolved_symbol = &implicit_declaration,
};
ref.PushReferenceComponent(implicit_ref);
return;
}
}
// For all other cases, grow the reference chain deeper.
// For type references, which may contained named parameters,
// when encountering the first unqualified reference, establish its
// reference node as the point from which named parameter references
// get added as siblings.
// e.g. "A#(.B(...), .C(...))" would result in a reference tree:
// A -+- ::B
// |
// \- ::C
reference_branch_point_ = ref.PushReferenceComponent(new_ref);
}
void Visit(const SyntaxTreeLeaf& leaf) final {
const auto tag = leaf.Tag().tag;
VLOG(1) << __FUNCTION__ << " [leaf]: " << VerboseToken(leaf.get());
switch (tag) {
case verilog_tokentype::SymbolIdentifier:
HandleIdentifier(leaf);
break;
case verilog_tokentype::TK_SCOPE_RES: // "::"
case '.':
last_hierarchy_operator_ = &leaf.get();
break;
default:
break;
}
VLOG(1) << "end " << __FUNCTION__ << " [leaf]:" << VerboseToken(leaf.get());
}
// Distinguish between '.' and "::" hierarchy in reference components.
ReferenceType InferReferenceType() const {
CHECK(!reference_builders_.empty())
<< "Not currently in a reference context.";
const DependentReferences& ref(reference_builders_.top());
if (ref.Empty() || last_hierarchy_operator_ == nullptr) {
// The root component is always treated as unqualified.
// Out-of-line definitions' base/outer references must be resolved
// immediately.
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kQualifiedId, // out-of-line
NodeEnum::kFunctionHeader})) {
return ReferenceType::kImmediate;
}
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kQualifiedId, // out-of-line
NodeEnum::kTaskHeader})) {
return ReferenceType::kImmediate;
}
return ReferenceType::kUnqualified;
}
if (Context().DirectParentIs(NodeEnum::kParamByName)) {
// Even though named parameters are referenced with ".PARAM",
// they are branched off of a base reference that already points
// to the type whose scope should be used, so no additional typeof()
// indirection is needed.
return ReferenceType::kDirectMember;
}
return ABSL_DIE_IF_NULL(last_hierarchy_operator_)->token_enum() == '.'
? ReferenceType::kMemberOfTypeOfParent
: ReferenceType::kDirectMember;
}
bool QualifiedIdComponentInLastPosition() const {
const SyntaxTreeNode* qualified_id =
Context().NearestParentWithTag(NodeEnum::kQualifiedId);
const SyntaxTreeNode* unqualified_id =
Context().NearestParentWithTag(NodeEnum::kUnqualifiedId);
return ABSL_DIE_IF_NULL(qualified_id)->children().back().get() ==
unqualified_id;
}
// Does the context necessitate that the symbol being referenced have a
// particular metatype?
SymbolMetaType InferMetaType() const {
const DependentReferences& ref(reference_builders_.top());
// Out-of-line definitions' base/outer references must be resolved
// immediately to a class.
// Member references (inner) is a function or task, depending on header
// type.
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kQualifiedId, // out-of-line
NodeEnum::kFunctionHeader})) {
return ref.Empty() ? SymbolMetaType::kClass : SymbolMetaType::kFunction;
}
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kQualifiedId, // out-of-line
NodeEnum::kTaskHeader})) {
return ref.Empty() ? SymbolMetaType::kClass : SymbolMetaType::kTask;
}
// TODO: import references bases must be resolved as
// SymbolMetaType::kPackage.
if (Context().DirectParentIs(NodeEnum::kActualNamedPort)) {
return SymbolMetaType::kDataNetVariableInstance;
}
if (Context().DirectParentIs(NodeEnum::kParamByName)) {
return SymbolMetaType::kParameter;
}
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kLocalRoot,
NodeEnum::kFunctionCall})) {
// bare call like "function_name(...)"
return SymbolMetaType::kCallable;
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kQualifiedId,
NodeEnum::kLocalRoot, NodeEnum::kFunctionCall})) {
// qualified call like "pkg_or_class::function_name(...)"
// Only the last component needs to be callable.
if (QualifiedIdComponentInLastPosition()) {
return SymbolMetaType::kCallable;
}
// TODO(fangism): could require parents to be kPackage or kClass
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kMethodCallExtension})) {
// method call like "obj.method_name(...)"
return SymbolMetaType::kCallable;
// TODO(fangism): check that method is non-static
}
if (Context().DirectParentsAre(
{NodeEnum::kUnqualifiedId, NodeEnum::kExtendsList})) {
// e.g. "base" in "class derived extends base;"
return SymbolMetaType::kClass;
}
if (Context().DirectParentsAre({NodeEnum::kUnqualifiedId,
NodeEnum::kQualifiedId,
NodeEnum::kExtendsList})) {
// base class is a qualified type like "pkg_or_class::class_name"
// Only the last component needs to be a type.
if (QualifiedIdComponentInLastPosition()) {
return SymbolMetaType::kClass;
}
// TODO(fangism): could require parents to be kPackage or kClass
}
// Default: no specific metatype.
return SymbolMetaType::kUnspecified;
}
// Creates a named element in the current scope.
// Suitable for SystemVerilog language elements: functions, tasks, packages,
// classes, modules, etc...
SymbolTableNode* EmplaceElementInCurrentScope(const verible::Symbol& element,
absl::string_view name,
SymbolMetaType metatype) {
const auto p =
current_scope_->TryEmplace(name, SymbolInfo{
.metatype = metatype,
.file_origin = source_,
.syntax_origin = &element,
});
if (!p.second) {
DiagnoseSymbolAlreadyExists(name);
}
return &p.first->second; // scope of the new (or pre-existing symbol)
}
// Creates a named typed element in the current scope.
// Suitable for SystemVerilog language elements: nets, parameter, variables,
// instances, functions (using their return types).
SymbolTableNode& EmplaceTypedElementInCurrentScope(
const verible::Symbol& element, absl::string_view name,
SymbolMetaType metatype) {
VLOG(1) << __FUNCTION__ << ": " << name << " in " << CurrentScopeFullPath();
VLOG(1) << " type info: " << *ABSL_DIE_IF_NULL(declaration_type_info_);
VLOG(1) << " full text: " << AutoTruncate{StringSpanOfSymbol(element), 40};
const auto p = current_scope_->TryEmplace(
name,
SymbolInfo{
.metatype = metatype,
.file_origin = source_,
.syntax_origin = &element,
// associate this instance with its declared type
.declared_type = *ABSL_DIE_IF_NULL(declaration_type_info_), // copy
});
if (!p.second) {
DiagnoseSymbolAlreadyExists(name);
}
VLOG(1) << "end of " << __FUNCTION__ << ": " << name;
return p.first->second; // scope of the new (or pre-existing symbol)
}
// Creates a named element in the current scope, and traverses its subtree
// inside the new element's scope.
// Returns the new scope.
SymbolTableNode* DeclareScopedElementAndDescend(const SyntaxTreeNode& element,
absl::string_view name,
SymbolMetaType type) {
SymbolTableNode* enter_scope =
EmplaceElementInCurrentScope(element, name, type);
Descend(element, enter_scope);
return enter_scope;
}
void DeclareModule(const SyntaxTreeNode& module) {
DeclareScopedElementAndDescend(module, GetModuleName(module).get().text(),
SymbolMetaType::kModule);
}
absl::string_view GetScopeNameFromGenerateBody(const SyntaxTreeNode& body) {
if (body.MatchesTag(NodeEnum::kGenerateBlock)) {
const TokenInfo* label =
GetBeginLabelTokenInfo(GetGenerateBlockBegin(body));
if (label != nullptr) {
// TODO: Check for a matching end-label here, and if its name matches
// the begin label, then immediately create a resolved reference because
// it only makes sense for it resolve to this begin.
// Otherwise, do nothing with the end label.
return label->text();
}
}
return current_scope_->Value().CreateAnonymousScope("generate");
}
void DeclareGenerateIf(const SyntaxTreeNode& generate_if) {
const SyntaxTreeNode& body(GetIfClauseGenerateBody(generate_if));
DeclareScopedElementAndDescend(generate_if,
GetScopeNameFromGenerateBody(body),
SymbolMetaType::kGenerate);
}
void DeclareGenerateElse(const SyntaxTreeNode& generate_else) {
const SyntaxTreeNode& body(GetElseClauseGenerateBody(generate_else));
if (body.MatchesTag(NodeEnum::kConditionalGenerateConstruct)) {
// else-if chained. Flatten the else block by not creating a new scope
// and let the if-clause inside create a scope directly under the current
// scope.
Descend(body);
} else {
DeclareScopedElementAndDescend(generate_else,
GetScopeNameFromGenerateBody(body),
SymbolMetaType::kGenerate);
}
}
void DeclarePackage(const SyntaxTreeNode& package) {
DeclareScopedElementAndDescend(package, GetPackageNameToken(package).text(),
SymbolMetaType::kPackage);
}
void DeclareClass(const SyntaxTreeNode& class_node) {
DeclareScopedElementAndDescend(class_node,
GetClassName(class_node).get().text(),
SymbolMetaType::kClass);
}
void DeclareTask(const SyntaxTreeNode& task_node) {
const ValueSaver<SymbolTableNode*> reserve_for_task_decl(
¤t_scope_); // no scope change yet
Descend(task_node);
}
void DeclareFunction(const SyntaxTreeNode& function_node) {
// Reserve a slot for the function's scope on the stack, but do not set it
// until we add it in HandleIdentifier(). This deferral allows us to
// evaluate the return type of the declared function as a reference in the
// current context.
const ValueSaver<SymbolTableNode*> reserve_for_function_decl(
¤t_scope_); // no scope change yet
Descend(function_node);
}
void DeclarePorts(const SyntaxTreeNode& port_list) {
// For out-of-line function declarations, do not re-declare ports that
// already came from the method prototype.
// We designate the prototype as the source-of-truth because in Verilog,
// port *names* are part of the public interface (allowing calling with
// named parameter assignments, unlike C++ function calls).
// LRM 8.24: "The out-of-block method declaration shall match the prototype
// declaration exactly, with the following exceptions..."
{
const SyntaxTreeNode* function_header =
Context().NearestParentMatching([](const SyntaxTreeNode& node) {
return node.MatchesTag(NodeEnum::kFunctionHeader);
});
if (function_header != nullptr) {
const SyntaxTreeNode& id = verible::SymbolCastToNode(
*ABSL_DIE_IF_NULL(GetFunctionHeaderId(*function_header)));
if (id.MatchesTag(NodeEnum::kQualifiedId)) {