forked from chipsalliance/verible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexing_facts_tree_extractor.cc
2014 lines (1723 loc) · 71.7 KB
/
indexing_facts_tree_extractor.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/tools/kythe/indexing_facts_tree_extractor.h"
#include <iostream>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/strip.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/tree_context_visitor.h"
#include "common/text/tree_utils.h"
#include "common/util/file_util.h"
#include "common/util/logging.h"
#include "common/util/tree_operations.h"
#include "verilog/CST/class.h"
#include "verilog/CST/declaration.h"
#include "verilog/CST/functions.h"
#include "verilog/CST/identifier.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/statement.h"
#include "verilog/CST/tasks.h"
#include "verilog/CST/type.h"
#include "verilog/CST/verilog_matchers.h"
#include "verilog/CST/verilog_nonterminals.h"
#include "verilog/CST/verilog_tree_print.h"
#include "verilog/analysis/verilog_analyzer.h"
#include "verilog/analysis/verilog_project.h"
#include "verilog/tools/kythe/indexing_facts_tree.h"
#include "verilog/tools/kythe/indexing_facts_tree_context.h"
namespace verilog {
namespace kythe {
namespace {
using verible::Symbol;
using verible::SymbolKind;
using verible::SyntaxTreeLeaf;
using verible::SyntaxTreeNode;
using verible::TokenInfo;
using verible::TreeSearchMatch;
struct VerilogExtractionState {
// Multi-file tracker.
VerilogProject* const project;
// Keep track of which files (translation units, includes) have been
// extracted.
std::set<const VerilogSourceFile*> extracted_files;
};
// This class is used for traversing CST and extracting different indexing
// facts from CST nodes and constructs a tree of indexing facts.
class IndexingFactsTreeExtractor : public verible::TreeContextVisitor {
public:
IndexingFactsTreeExtractor(IndexingFactNode& file_list_facts_tree,
const VerilogSourceFile& source_file,
VerilogExtractionState* extraction_state,
std::vector<absl::Status>* errors)
: file_list_facts_tree_(file_list_facts_tree),
source_file_(source_file),
extraction_state_(extraction_state),
errors_(errors) {
const absl::string_view base = source_file_.GetTextStructure()->Contents();
root_.Value().AppendAnchor(
// Create the Anchor for file path node.
Anchor(source_file_.ResolvedPath()),
// Create the Anchor for text (code) node.
Anchor(base));
}
void Visit(const SyntaxTreeLeaf& leaf) final;
void Visit(const SyntaxTreeNode& node) final;
const IndexingFactNode& Root() const { return root_; }
IndexingFactNode TakeRoot() { return std::move(root_); }
private: // methods
// Extracts facts from module, intraface and program declarations.
void ExtractModuleOrInterfaceOrProgram(const SyntaxTreeNode& declaration_node,
IndexingFactType node_type);
// Extracts modules instantiations and creates its corresponding fact tree.
void ExtractModuleInstantiation(
const SyntaxTreeNode& data_declaration_node,
const std::vector<TreeSearchMatch>& gate_instances);
// Extracts endmodule, endinterface, endprogram and creates its corresponding
// fact tree.
void ExtractModuleOrInterfaceOrProgramEnd(
const SyntaxTreeNode& module_declaration_node);
// Extracts module, interface, program headers and creates its corresponding
// fact tree.
void ExtractModuleOrInterfaceOrProgramHeader(
const SyntaxTreeNode& module_declaration_node);
// Extracts modules ports and creates its corresponding fact tree.
// "has_propagated_type" determines if this port is "Non-ANSI" or not.
// e.g "module m(a, b, input c, d)" starting from "c" "has_propagated_type"
// will be true.
void ExtractModulePort(const SyntaxTreeNode& module_port_node,
bool has_propagated_type);
// Extracts "a" from "input a", "output a" and creates its corresponding fact
// tree.
void ExtractInputOutputDeclaration(
const SyntaxTreeNode& identifier_unpacked_dimensions);
// Extracts "a" from "wire a" and creates its corresponding fact tree.
void ExtractNetDeclaration(const SyntaxTreeNode& net_declaration_node);
// Extract package declarations and creates its corresponding facts tree.
void ExtractPackageDeclaration(
const SyntaxTreeNode& package_declaration_node);
// Extract macro definitions and explores its arguments and creates its
// corresponding facts tree.
void ExtractMacroDefinition(const SyntaxTreeNode& preprocessor_definition);
// Extract macro calls and explores its arguments and creates its
// corresponding facts tree.
void ExtractMacroCall(const SyntaxTreeNode& macro_call);
// Extract macro names from "kMacroIdentifiers" which are considered
// references to macros and creates its corresponding facts tree.
void ExtractMacroReference(const SyntaxTreeLeaf& macro_identifier);
// Extracts Include statements and creates its corresponding fact tree.
void ExtractInclude(const SyntaxTreeNode& preprocessor_include);
// Extracts function and creates its corresponding fact tree.
void ExtractFunctionDeclaration(
const SyntaxTreeNode& function_declaration_node);
// Extracts class constructor and creates its corresponding fact tree.
void ExtractClassConstructor(const SyntaxTreeNode& class_constructor);
// Extracts task and creates its corresponding fact tree.
void ExtractTaskDeclaration(const SyntaxTreeNode& task_declaration_node);
// Extracts function or task call and creates its corresponding fact tree.
void ExtractFunctionOrTaskCall(const SyntaxTreeNode& function_call_node);
// Extracts function or task call tagged with "kMethodCallExtension" (treated
// as kFunctionOrTaskCall in facts tree) and creates its corresponding fact
// tree.
void ExtractMethodCallExtension(const SyntaxTreeNode& call_extension_node);
// Extracts members tagged with "kHierarchyExtension" (treated as
// kMemberReference in facts tree) and creates its corresponding fact tree.
void ExtractMemberExtension(const SyntaxTreeNode& hierarchy_extension_node);
// Extracts function or task ports and parameters.
void ExtractFunctionOrTaskOrConstructorPort(
const SyntaxTreeNode& function_declaration_node);
// Extracts classes and creates its corresponding fact tree.
void ExtractClassDeclaration(const SyntaxTreeNode& class_declaration);
// Extracts class instances and creates its corresponding fact tree.
void ExtractClassInstances(
const SyntaxTreeNode& data_declaration,
const std::vector<TreeSearchMatch>& class_instances);
// Extracts primitive types declarations tagged with kRegisterVariable and
// creates its corresponding fact tree.
void ExtractRegisterVariable(const SyntaxTreeNode& register_variable);
// Extracts primitive types declarations tagged with
// kVariableDeclarationAssignment and creates its corresponding fact tree.
void ExtractVariableDeclarationAssignment(
const SyntaxTreeNode& variable_declaration_assignment);
// Extracts enum name and creates its corresponding fact tree.
void ExtractEnumName(const SyntaxTreeNode& enum_name);
// Extracts type declaration preceeded with "typedef" and creates its
// corresponding fact tree.
void ExtractTypeDeclaration(const SyntaxTreeNode& type_declaration);
// Extracts pure virtual functions and creates its corresponding fact tree.
void ExtractPureVirtualFunction(const SyntaxTreeNode& function_prototype);
// Extracts pure virtual tasks and creates its corresponding fact tree.
void ExtractPureVirtualTask(const SyntaxTreeNode& task_prototype);
// Extracts function header and creates its corresponding fact tree.
void ExtractFunctionHeader(const SyntaxTreeNode& function_header,
IndexingFactNode& function_node);
// Extracts task header and creates its corresponding fact tree.
void ExtractTaskHeader(const SyntaxTreeNode& task_header,
IndexingFactNode& task_node);
// Extracts enum type declaration preceeded with "typedef" and creates its
// corresponding fact tree.
void ExtractEnumTypeDeclaration(const SyntaxTreeNode& enum_type_declaration);
// Extracts struct type declaration preceeded with "typedef" and creates its
// corresponding fact tree.
void ExtractStructUnionTypeDeclaration(const SyntaxTreeNode& type_declaration,
const SyntaxTreeNode& struct_type);
// Extracts struct declaration and creates its corresponding fact tree.
void ExtractStructUnionDeclaration(
const SyntaxTreeNode& struct_type,
const std::vector<TreeSearchMatch>& variables_matched);
// Extracts struct and union members and creates its corresponding fact tree.
void ExtractDataTypeImplicitIdDimensions(
const SyntaxTreeNode& data_type_implicit_id_dimensions);
// Extracts variable definitions preceeded with some data type and creates its
// corresponding fact tree.
// e.g "some_type var1;"
void ExtractTypedVariableDefinition(
const Symbol& type_identifier,
const std::vector<TreeSearchMatch>& variables_matched);
// Extracts leaves tagged with SymbolIdentifier and creates its facts
// tree. This should only be reached in case of free variable references.
// e.g "assign out = in & in2."
// Other extraction functions should terminate in case the inner
// SymbolIdentifiers are extracted.
void ExtractSymbolIdentifier(const SyntaxTreeLeaf& symbol_identifier);
// Extracts nodes tagged with "kUnqualifiedId".
void ExtractUnqualifiedId(const SyntaxTreeNode& unqualified_id);
// Extracts parameter declarations and creates its corresponding fact tree.
void ExtractParamDeclaration(const SyntaxTreeNode& param_declaration);
// Extracts module instantiation named ports and creates its corresponding
// fact tree.
void ExtractModuleNamedPort(const SyntaxTreeNode& actual_named_port);
// Extracts package imports and creates its corresponding fact tree.
void ExtractPackageImport(const SyntaxTreeNode& package_import_item);
// Extracts qualified ids and creates its corresponding fact tree.
// e.g "pkg::member" or "class::member".
void ExtractQualifiedId(const SyntaxTreeNode& qualified_id);
// Extracts initializations in for loop and creates its corresponding fact
// tree. e.g from "for(int i = 0, j = k; ...)" extracts "i", "j" and "k".
void ExtractForInitialization(const SyntaxTreeNode& for_initialization);
// Extracts param references and the actual references names.
// e.g from "counter #(.N(r))" extracts "N".
void ExtractParamByName(const SyntaxTreeNode& param_by_name);
// Extracts new scope and assign unique id to it.
// specifically, intended for conditional/loop generate constructs.
void ExtractAnonymousScope(const SyntaxTreeNode& node);
// Determines how to deal with the given data declaration node as it may be
// module instance, class instance or primitive variable.
void ExtractDataDeclaration(const SyntaxTreeNode& data_declaration);
// Moves the anchors and children from the the last extracted node in
// "facts_tree_context_", adds them to the new_node and pops remove the last
// extracted node.
void MoveAndDeleteLastExtractedNode(IndexingFactNode& new_node);
absl::string_view FileContent() {
return source_file_.GetTextStructure()->Contents();
}
private: // data members
// The Root of the constructed facts tree.
IndexingFactNode root_{IndexingNodeData(IndexingFactType::kFile)};
// Keeps track of indexing facts tree ancestors as the visitor traverses CST.
IndexingFactsTreeContext facts_tree_context_;
// "IndexingFactNode" with tag kFileList which holds the extracted indexing
// facts trees of the files in the ordered file list. The extracted files will
// be children of this node and ordered as they are given in the ordered file
// list.
IndexingFactNode& file_list_facts_tree_;
// The current file being extracted.
const VerilogSourceFile& source_file_;
// The project configuration used to find included files.
VerilogExtractionState* const extraction_state_;
// Processing errors.
std::vector<absl::Status>* errors_;
// Counter used as an id for the anonymous scopes.
int next_anonymous_id = 0;
};
// Given a root to CST this function traverses the tree, extracts and constructs
// the indexing facts tree for one file.
IndexingFactNode BuildIndexingFactsTree(
IndexingFactNode& file_list_facts_tree,
const VerilogSourceFile& source_file,
VerilogExtractionState* extraction_state,
std::vector<absl::Status>* errors) {
VLOG(1) << __FUNCTION__ << ": file: " << source_file;
IndexingFactsTreeExtractor visitor(file_list_facts_tree, source_file,
extraction_state, errors);
if (source_file.Status().ok()) {
const auto& syntax_tree = source_file.GetTextStructure()->SyntaxTree();
if (syntax_tree != nullptr) {
VLOG(2) << "syntax:\n" << verible::RawTreePrinter(*syntax_tree);
syntax_tree->Accept(&visitor);
}
}
const PrintableIndexingFactNode debug_node(
visitor.Root(), source_file.GetTextStructure()->Contents());
VLOG(2) << "built facts tree: " << debug_node;
return visitor.TakeRoot();
}
} // namespace
IndexingFactNode ExtractFiles(absl::string_view file_list_path,
VerilogProject* project,
const std::vector<std::string>& file_names,
std::vector<absl::Status>* errors) {
VLOG(1) << __FUNCTION__;
// Open all of the translation units.
for (absl::string_view file_name : file_names) {
const auto status_or_file = project->OpenTranslationUnit(file_name);
if (!status_or_file.ok()) {
if (errors != nullptr) {
errors->push_back(status_or_file.status());
} else {
LOG(ERROR) << "Failed to open file " << file_name << ": "
<< status_or_file.status();
}
}
// For now, collect all diagnostics at the end.
// TODO(fangism): offer a mode to exit-early if there are file-not-found
// or read-permission issues (fail-fast, alert-user).
}
// Create a node to hold the path and root of the ordered file list, group
// all the files and acts as a ordered file list of these files.
IndexingFactNode file_list_facts_tree(
IndexingNodeData(IndexingFactType::kFileList, Anchor(file_list_path),
Anchor(project->TranslationUnitRoot())));
VerilogExtractionState project_extraction_state{project};
// pre-allocate file nodes with the number of translation units
file_list_facts_tree.Children().reserve(file_names.size());
for (absl::string_view file_name : file_names) {
auto* translation_unit = project->LookupRegisteredFile(file_name);
if (translation_unit == nullptr) continue;
const auto parse_status = translation_unit->Parse();
// status is also stored in translation_unit for later retrieval.
if (parse_status.ok()) {
file_list_facts_tree.Children().push_back(
BuildIndexingFactsTree(file_list_facts_tree, *translation_unit,
&project_extraction_state, errors));
} else {
if (errors != nullptr) {
errors->push_back(parse_status);
} else {
LOG(WARNING) << "Failed to parse file " << file_name << ": "
<< parse_status;
}
}
project->RemoveRegisteredFile(file_name);
}
VLOG(1) << "end of " << __FUNCTION__;
return file_list_facts_tree;
}
void IndexingFactsTreeExtractor::Visit(const SyntaxTreeNode& node) {
const auto tag = static_cast<verilog::NodeEnum>(node.Tag().tag);
VLOG(3) << __FUNCTION__ << ", tag: " << tag;
switch (tag) {
case NodeEnum ::kDescriptionList: {
// Adds the current root to facts tree context to keep track of the parent
// node so that it can be used to construct the tree and add children to
// it.
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &root_);
TreeContextVisitor::Visit(node);
break;
}
case NodeEnum::kInterfaceDeclaration: {
ExtractModuleOrInterfaceOrProgram(node, IndexingFactType::kInterface);
break;
}
case NodeEnum::kModuleDeclaration: {
ExtractModuleOrInterfaceOrProgram(node, IndexingFactType::kModule);
break;
}
case NodeEnum::kProgramDeclaration: {
ExtractModuleOrInterfaceOrProgram(node, IndexingFactType::kProgram);
break;
}
case NodeEnum::kDataDeclaration: {
ExtractDataDeclaration(node);
break;
}
case NodeEnum::kIdentifierUnpackedDimensions: {
ExtractInputOutputDeclaration(node);
break;
}
case NodeEnum ::kNetDeclaration: {
ExtractNetDeclaration(node);
break;
}
case NodeEnum::kPackageDeclaration: {
ExtractPackageDeclaration(node);
break;
}
case NodeEnum::kPreprocessorDefine: {
ExtractMacroDefinition(node);
break;
}
case NodeEnum::kMacroCall: {
ExtractMacroCall(node);
break;
}
case NodeEnum::kFunctionDeclaration: {
ExtractFunctionDeclaration(node);
break;
}
case NodeEnum::kTaskDeclaration: {
ExtractTaskDeclaration(node);
break;
}
case NodeEnum::kClassConstructor: {
ExtractClassConstructor(node);
break;
}
case NodeEnum::kFunctionCall: {
ExtractFunctionOrTaskCall(node);
break;
}
case NodeEnum::kMethodCallExtension: {
ExtractMethodCallExtension(node);
break;
}
case NodeEnum::kHierarchyExtension: {
ExtractMemberExtension(node);
break;
}
case NodeEnum::kClassDeclaration: {
ExtractClassDeclaration(node);
break;
}
case NodeEnum::kParamDeclaration: {
ExtractParamDeclaration(node);
break;
}
case NodeEnum::kActualNamedPort: {
ExtractModuleNamedPort(node);
break;
}
case NodeEnum::kPackageImportItem: {
ExtractPackageImport(node);
break;
}
case NodeEnum::kQualifiedId: {
ExtractQualifiedId(node);
break;
}
case NodeEnum::kForInitialization: {
ExtractForInitialization(node);
break;
}
case NodeEnum::kDataTypeImplicitIdDimensions: {
ExtractDataTypeImplicitIdDimensions(node);
break;
}
case NodeEnum::kParamByName: {
ExtractParamByName(node);
break;
}
case NodeEnum::kPreprocessorInclude: {
ExtractInclude(node);
break;
}
case NodeEnum::kRegisterVariable: {
ExtractRegisterVariable(node);
break;
}
case NodeEnum::kFunctionPrototype: {
ExtractPureVirtualFunction(node);
break;
}
case NodeEnum::kTaskPrototype: {
ExtractPureVirtualTask(node);
break;
}
case NodeEnum::kVariableDeclarationAssignment: {
ExtractVariableDeclarationAssignment(node);
break;
}
case NodeEnum::kEnumName: {
ExtractEnumName(node);
break;
}
case NodeEnum::kTypeDeclaration: {
ExtractTypeDeclaration(node);
break;
}
case NodeEnum::kLoopGenerateConstruct:
case NodeEnum::kIfClause:
case NodeEnum::kFinalStatement:
case NodeEnum::kInitialStatement:
case NodeEnum::kGenerateElseBody:
case NodeEnum::kElseClause:
case NodeEnum::kGenerateIfClause:
case NodeEnum::kForLoopStatement:
case NodeEnum::kDoWhileLoopStatement:
case NodeEnum::kWhileLoopStatement:
case NodeEnum::kForeachLoopStatement:
case NodeEnum::kRepeatLoopStatement:
case NodeEnum::kForeverLoopStatement: {
ExtractAnonymousScope(node);
break;
}
case NodeEnum::kUnqualifiedId: {
ExtractUnqualifiedId(node);
break;
}
default: {
TreeContextVisitor::Visit(node);
}
}
VLOG(3) << "end of " << __FUNCTION__ << ", tag: " << tag;
}
void IndexingFactsTreeExtractor::Visit(const SyntaxTreeLeaf& leaf) {
switch (leaf.get().token_enum()) {
case verilog_tokentype::SymbolIdentifier: {
ExtractSymbolIdentifier(leaf);
break;
}
default: {
break;
}
}
}
void IndexingFactsTreeExtractor::ExtractSymbolIdentifier(
const SyntaxTreeLeaf& symbol_identifier) {
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableReference,
Anchor(symbol_identifier.get(), FileContent())));
}
void IndexingFactsTreeExtractor::ExtractDataDeclaration(
const SyntaxTreeNode& data_declaration) {
// For module instantiations
const std::vector<TreeSearchMatch> gate_instances =
FindAllGateInstances(data_declaration);
if (!gate_instances.empty()) {
ExtractModuleInstantiation(data_declaration, gate_instances);
return;
}
// For bit, int and classes
const std::vector<TreeSearchMatch> register_variables =
FindAllRegisterVariables(data_declaration);
if (!register_variables.empty()) {
// for classes.
const std::vector<TreeSearchMatch> class_instances =
verible::SearchSyntaxTree(data_declaration, NodekClassNew());
if (!class_instances.empty()) {
ExtractClassInstances(data_declaration, register_variables);
return;
}
// for struct and union types.
const SyntaxTreeNode* type_node =
GetStructOrUnionOrEnumTypeFromDataDeclaration(data_declaration);
// Ignore if this isn't a struct or union type.
if (type_node != nullptr &&
NodeEnum(type_node->Tag().tag) != NodeEnum::kEnumType) {
ExtractStructUnionDeclaration(*type_node, register_variables);
return;
}
// In case "some_type var1".
const Symbol* type_identifier =
GetTypeIdentifierFromDataDeclaration(data_declaration);
if (type_identifier != nullptr) {
ExtractTypedVariableDefinition(*type_identifier, register_variables);
return;
}
// Traverse the children to extract inner nodes.
TreeContextVisitor::Visit(data_declaration);
return;
}
const std::vector<TreeSearchMatch> variable_declaration_assign =
FindAllVariableDeclarationAssignment(data_declaration);
if (!variable_declaration_assign.empty()) {
// for classes.
const std::vector<TreeSearchMatch> class_instances =
verible::SearchSyntaxTree(data_declaration, NodekClassNew());
if (!class_instances.empty()) {
ExtractClassInstances(data_declaration, variable_declaration_assign);
return;
}
// for struct and union types.
const SyntaxTreeNode* type_node =
GetStructOrUnionOrEnumTypeFromDataDeclaration(data_declaration);
// Ignore if this isn't a struct or union type.
if (type_node != nullptr &&
NodeEnum(type_node->Tag().tag) != NodeEnum::kEnumType) {
ExtractStructUnionDeclaration(*type_node, variable_declaration_assign);
return;
}
// In case "some_type var1".
const Symbol* type_identifier =
GetTypeIdentifierFromDataDeclaration(data_declaration);
if (type_identifier != nullptr) {
ExtractTypedVariableDefinition(*type_identifier,
variable_declaration_assign);
return;
}
// Traverse the children to extract inner nodes.
TreeContextVisitor::Visit(data_declaration);
return;
}
// Traverse the children to extract inner nodes.
TreeContextVisitor::Visit(data_declaration);
}
void IndexingFactsTreeExtractor::ExtractTypedVariableDefinition(
const Symbol& type_identifier,
const std::vector<TreeSearchMatch>& variables_matche) {
IndexingFactNode type_node(
IndexingNodeData{IndexingFactType::kDataTypeReference});
type_identifier.Accept(this);
MoveAndDeleteLastExtractedNode(type_node);
{
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &type_node);
for (const TreeSearchMatch& variable : variables_matche) {
variable.match->Accept(this);
}
}
facts_tree_context_.top().Children().push_back(std::move(type_node));
}
void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgram(
const SyntaxTreeNode& declaration_node, IndexingFactType node_type) {
IndexingFactNode facts_node(IndexingNodeData{node_type});
{
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_,
&facts_node);
ExtractModuleOrInterfaceOrProgramHeader(declaration_node);
ExtractModuleOrInterfaceOrProgramEnd(declaration_node);
const SyntaxTreeNode* item_list = GetModuleItemList(declaration_node);
if (item_list) Visit(*item_list);
}
facts_tree_context_.top().Children().push_back(std::move(facts_node));
}
void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramHeader(
const SyntaxTreeNode& module_declaration_node) {
// Extract module name e.g from "module my_module" extracts "my_module".
const SyntaxTreeLeaf* module_name_leaf =
GetModuleName(module_declaration_node);
if (!module_name_leaf) return;
facts_tree_context_.top().Value().AppendAnchor(
Anchor(module_name_leaf->get(), FileContent()));
// Extract parameters if exist.
const SyntaxTreeNode* param_declaration_list =
GetParamDeclarationListFromModuleDeclaration(module_declaration_node);
if (param_declaration_list != nullptr) {
Visit(*param_declaration_list);
}
// Extracting module ports e.g. (input a, input b).
// Ports are treated as children of the module.
const SyntaxTreeNode* port_list =
GetModulePortDeclarationList(module_declaration_node);
if (port_list == nullptr) {
return;
}
// This boolean is used to distinguish between ANSI and Non-ANSI module
// ports. e.g in this case: module m(a, b); has_propagated_type will be
// false as no type has been countered.
//
// in case like:
// module m(a, b, input x, y)
// for "a", "b" the boolean will be false but for "x", "y" the boolean will
// be true.
//
// The boolean is used to determine whether this the fact for this variable
// should be a reference or a defintiion.
bool has_propagated_type = false;
for (const auto& port : port_list->children()) {
if (port->Kind() == SymbolKind::kLeaf) continue;
const SyntaxTreeNode& port_node = SymbolCastToNode(*port);
const auto tag = static_cast<verilog::NodeEnum>(port_node.Tag().tag);
if (tag == NodeEnum::kPortDeclaration) {
has_propagated_type = true;
ExtractModulePort(port_node, has_propagated_type);
} else if (tag == NodeEnum::kPort) {
const SyntaxTreeNode* ref_port = GetPortReferenceFromPort(port_node);
if (ref_port) ExtractModulePort(*ref_port, has_propagated_type);
}
}
}
void IndexingFactsTreeExtractor::ExtractModulePort(
const SyntaxTreeNode& module_port_node, bool has_propagated_type) {
const auto tag = static_cast<verilog::NodeEnum>(module_port_node.Tag().tag);
// For extracting cases like:
// module m(input a, input b);
if (tag == NodeEnum::kPortDeclaration) {
const SyntaxTreeLeaf* leaf =
GetIdentifierFromModulePortDeclaration(module_port_node);
if (!leaf) return;
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(leaf->get(), FileContent())));
} else if (tag == NodeEnum::kPortReference) {
// For extracting Non-ANSI style ports:
// module m(a, b);
const SyntaxTreeLeaf* leaf =
GetIdentifierFromPortReference(module_port_node);
if (!leaf) return;
if (has_propagated_type) {
// Check if the last type was not a primitive type.
// e.g module (interface_type x, y).
if (is_leaf(facts_tree_context_.top()) ||
facts_tree_context_.top()
.Children()
.back()
.Value()
.GetIndexingFactType() !=
IndexingFactType::kDataTypeReference) {
// Append this as a variable definition.
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(leaf->get(), FileContent())));
} else {
// Append this as a child to previous kDataTypeReference.
facts_tree_context_.top().Children().back().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(leaf->get(), FileContent())));
}
} else {
// In case no preceeded data type.
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableReference,
Anchor(leaf->get(), FileContent())));
}
}
// Extract unpacked and packed dimensions.
for (const auto& child : module_port_node.children()) {
if (child == nullptr || child->Kind() == SymbolKind::kLeaf) {
continue;
}
const auto tag = static_cast<verilog::NodeEnum>(child->Tag().tag);
if (tag == NodeEnum::kUnqualifiedId) {
continue;
}
if (tag == NodeEnum::kDataType) {
const SyntaxTreeNode* data_type = GetTypeIdentifierFromDataType(*child);
// If not null this is a non primitive type and should create
// kDataTypeReference node for it.
// This data_type may be some class or interface type.
if (data_type != nullptr) {
// Create a node for this data type and append its anchor.
IndexingFactNode data_type_node(
IndexingNodeData{IndexingFactType::kDataTypeReference});
data_type->Accept(this);
MoveAndDeleteLastExtractedNode(data_type_node);
// Make the current port node child of this data type, remove it from
// the top node and push the kDataTypeRefernce Node.
data_type_node.Children().push_back(
std::move(facts_tree_context_.top().Children().back()));
facts_tree_context_.top().Children().back() = std::move(data_type_node);
continue;
}
}
child->Accept(this);
}
}
void IndexingFactsTreeExtractor::ExtractModuleNamedPort(
const SyntaxTreeNode& actual_named_port) {
const SyntaxTreeLeaf* named_port = GetActualNamedPortName(actual_named_port);
if (!named_port) return;
IndexingFactNode actual_port_node(
IndexingNodeData(IndexingFactType::kModuleNamedPort,
Anchor(named_port->get(), FileContent())));
{
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_,
&actual_port_node);
const Symbol* paren_group = GetActualNamedPortParenGroup(actual_named_port);
if (paren_group != nullptr) {
paren_group->Accept(this);
}
}
facts_tree_context_.top().Children().emplace_back(
std::move(actual_port_node));
}
void IndexingFactsTreeExtractor::ExtractInputOutputDeclaration(
const SyntaxTreeNode& identifier_unpacked_dimension) {
const SyntaxTreeLeaf* port_name_leaf =
GetSymbolIdentifierFromIdentifierUnpackedDimensions(
identifier_unpacked_dimension);
if (port_name_leaf) {
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(port_name_leaf->get(), FileContent())));
}
}
void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramEnd(
const SyntaxTreeNode& module_declaration_node) {
const SyntaxTreeLeaf* module_name =
GetModuleEndLabel(module_declaration_node);
if (module_name != nullptr) {
facts_tree_context_.top().Value().AppendAnchor(
Anchor(module_name->get(), FileContent()));
}
}
void IndexingFactsTreeExtractor::ExtractModuleInstantiation(
const SyntaxTreeNode& data_declaration_node,
const std::vector<TreeSearchMatch>& gate_instances) {
IndexingFactNode type_node(
IndexingNodeData{IndexingFactType::kDataTypeReference});
// Extract module type name.
const Symbol* type =
GetTypeIdentifierFromDataDeclaration(data_declaration_node);
if (type == nullptr) {
return;
}
// Extract module instance type and parameters.
type->Accept(this);
MoveAndDeleteLastExtractedNode(type_node);
// Module instantiations (data declarations) may declare multiple instances
// sharing the same type in a single statement e.g. bar b1(), b2().
//
// Loop through each instance and associate each declared id with the same
// type and create its corresponding facts tree node.
for (const TreeSearchMatch& instance : gate_instances) {
IndexingFactNode module_instance_node(
IndexingNodeData{IndexingFactType::kModuleInstance});
const TokenInfo* variable_name =
GetModuleInstanceNameTokenInfoFromGateInstance(*instance.match);
if (variable_name) {
module_instance_node.Value().AppendAnchor(
Anchor(*variable_name, FileContent()));
}
{
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_,
&module_instance_node);
const SyntaxTreeNode* paren_group =
GetParenGroupFromModuleInstantiation(*instance.match);
if (paren_group) Visit(*paren_group);
}
type_node.Children().push_back(std::move(module_instance_node));
}
facts_tree_context_.top().Children().push_back(std::move(type_node));
}
void IndexingFactsTreeExtractor::ExtractNetDeclaration(
const SyntaxTreeNode& net_declaration_node) {
// Nets are treated as children of the enclosing parent.
// Net declarations may declare multiple instances sharing the same type in
// a single statement.
const std::vector<const TokenInfo*> identifiers =
GetIdentifiersFromNetDeclaration(net_declaration_node);
// Loop through each instance and associate each declared id with the same
// type.
for (const TokenInfo* wire_token_info : identifiers) {
facts_tree_context_.top().Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(*wire_token_info, FileContent())));
}
}
void IndexingFactsTreeExtractor::ExtractPackageDeclaration(
const SyntaxTreeNode& package_declaration_node) {
IndexingFactNode package_node(IndexingNodeData{IndexingFactType::kPackage});
{
const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_,
&package_node);
// Extract package name.
const SyntaxTreeLeaf* pname = GetPackageNameLeaf(package_declaration_node);
if (pname) {
facts_tree_context_.top().Value().AppendAnchor(
Anchor(pname->get(), FileContent()));
}
// Extract package name after endpackage if exists.
const SyntaxTreeLeaf* package_end_name =
GetPackageNameEndLabel(package_declaration_node);
if (package_end_name != nullptr) {
facts_tree_context_.top().Value().AppendAnchor(
Anchor(package_end_name->get(), FileContent()));
}
// Visit package body it exists.
const Symbol* package_item_list =
GetPackageItemList(package_declaration_node);
if (package_item_list != nullptr) {
package_item_list->Accept(this);
}
}
facts_tree_context_.top().Children().push_back(std::move(package_node));
}
void IndexingFactsTreeExtractor::ExtractMacroDefinition(
const SyntaxTreeNode& preprocessor_definition) {
const SyntaxTreeLeaf* macro_name = GetMacroName(preprocessor_definition);
if (!macro_name) return;
IndexingFactNode macro_node(IndexingNodeData(
IndexingFactType::kMacro, Anchor(macro_name->get(), FileContent())));
// TODO(fangism): access directly, instead of searching.
const std::vector<TreeSearchMatch> args =
FindAllMacroDefinitionsArgs(preprocessor_definition);
for (const TreeSearchMatch& arg : args) {
const SyntaxTreeLeaf* macro_arg_name = GetMacroArgName(*arg.match);
if (macro_arg_name) {
macro_node.Children().emplace_back(
IndexingNodeData(IndexingFactType::kVariableDefinition,
Anchor(macro_arg_name->get(), FileContent())));
}
}
facts_tree_context_.top().Children().push_back(std::move(macro_node));
}
Anchor GetMacroAnchorFromTokenInfo(const TokenInfo& macro_token_info,
absl::string_view file_content) {
// Strip the prefix "`".
// e.g.
// `define TEN 0
// `TEN --> removes the `