forked from chipsalliance/verible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoexpand.cc
1725 lines (1550 loc) · 66.2 KB
/
autoexpand.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 2023 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/ls/autoexpand.h"
#include <algorithm>
#include <cstdint>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/node_hash_map.h"
#include "common/text/text_structure.h"
#include "re2/re2.h"
#include "verilog/CST/declaration.h"
#include "verilog/CST/dimensions.h"
#include "verilog/CST/expression.h"
#include "verilog/CST/identifier.h"
#include "verilog/CST/module.h"
#include "verilog/CST/net.h"
#include "verilog/CST/port.h"
#include "verilog/CST/type.h"
#include "verilog/CST/verilog_matchers.h" // IWYU pragma: keep
#include "verilog/formatting/format_style_init.h"
#include "verilog/formatting/formatter.h"
namespace verilog {
using verible::FindLastSubtree;
using verible::Interval;
using verible::LineColumn;
using verible::LineColumnRange;
using verible::StringSpanOfSymbol;
using verible::Symbol;
using verible::SymbolCastToNode;
using verible::SymbolKind;
using verible::SymbolPtr;
using verible::SyntaxTreeLeaf;
using verible::SyntaxTreeNode;
using verible::TextStructureView;
using verible::TokenInfo;
using verible::TreeSearchMatch;
using verible::lsp::CodeAction;
using verible::lsp::CodeActionParams;
using verible::lsp::TextEdit;
using verilog::VerilogAnalyzer;
using verilog::formatter::FormatStyle;
using verilog::formatter::InitializeFromFlags;
namespace {
// Possible kinds of AUTO
enum class AutoKind {
kAutoarg,
kAutoinst,
kAutoinput,
kAutoinout,
kAutooutput,
kAutowire,
kAutoreg,
};
// Takes a TextStructureView and generates LSP TextEdits for AUTO expansion
class AutoExpander {
public:
// TODO: move most of these items to private
// An AUTO matched in the buffer text
struct Match {
absl::string_view auto_span; // Span of the entire AUTO
absl::string_view comment_span; // Span of the AUTO pragma comment
};
// A single AUTO expansion in terms of the replaced span and expanded text
struct Expansion {
absl::string_view replaced_span; // Span that is to be replaced
std::string new_text; // Text to replace the span with
};
// Represents a port connection
struct Connection {
std::string port_name; // The name of the port in the module instance
bool emit_dimensions; // If true, when emitted, the connection should be
// annotated with the signal dimensions
};
// Stores information about the instance the port is connected to
struct ConnectedInstance {
std::optional<absl::string_view> instance; // Name of the instance a port
// is connected to
absl::string_view type; // Type of the instance a port is connected to
};
// A SystemVerilog range [msb:lsb]
struct DimensionRange {
int64_t msb;
int64_t lsb;
};
// A dimension can be a range, an unsigned integer, or, if it cannot be
// interpreted as one of these, a string
using Dimension = std::variant<absl::string_view, size_t, DimensionRange>;
// Iterates through the given dimension vectors and returns a new one with
// each element being the maximum of corresponding original dimensions.
static std::vector<Dimension> MaxDimensions(
const std::vector<Dimension> &first,
const std::vector<Dimension> &second);
// Representation of a net-like, base type for Port and Wire (you probably
// want to use those)
struct Net {
std::string name; // Name of the net
std::vector<ConnectedInstance> conn_inst; // What instances is
// it connected to?
std::vector<Dimension> packed_dimensions; // This net's packed dimensions
std::vector<Dimension> unpacked_dimensions; // This net's unpacked
// dimensions
// Writes the port's identifier with packed and unpacked dimensions to the
// output stream
void EmitIdWithDimensions(std::ostream &output) const;
// Returns true if the port is connected to any instance
bool IsConnected() const { return !conn_inst.empty(); }
// Adds the given connected instance to the net's list of connections, and
// makes the packed dimensions the max of the current dimensions and the
// ones provided
void AddConnection(const ConnectedInstance &connected,
const std::vector<Dimension> &new_packed_dimensions) {
conn_inst.push_back(connected);
packed_dimensions =
AutoExpander::MaxDimensions(packed_dimensions, new_packed_dimensions);
}
};
// A port, with direction and some meta-info
struct Port final : Net {
enum class Direction { kInput, kInout, kOutput };
enum class Declaration { kUndeclared, kAutogenerated, kDeclared };
Direction direction; // Direction of the port
Declaration declaration; // Is it user-declared or autogenerated
absl::string_view::const_iterator it; // Location of the port's declaration
// in the source file
// Writes the port's direction to the output stream
void EmitDirection(std::ostream &output) const;
// Writes a comment describing the port's connection to the output stream
void EmitConnectionComment(std::ostream &output) const;
};
// A wire generated by AUTO expansion
struct Wire final : Net {
// Writes a comment describing the port's connection to the output stream
void EmitConnectionComment(std::ostream &output) const;
};
// Represents an AUTO_TEMPLATE
struct Template {
using Map = absl::flat_hash_map<absl::string_view, std::vector<Template>>;
absl::string_view::const_iterator it; // Location of the template in the
// source file
std::shared_ptr<RE2> instance_name_re; // Regex for matching the instance
// name. Shared between templates
// declared at the same place
absl::flat_hash_map<absl::string_view, Connection>
connections; // Map of instance ports ports to connected module ports
};
enum class PortDeclStyle {
kColonSeparator,
kCommaSeparator,
kCommaSeparatorExceptLast
};
// Module information relevant to AUTO expansion
class Module {
public:
explicit Module(const Symbol &module)
: symbol_(module), name_(GetModuleName(symbol_)->get().text()) {
RetrieveModuleHeaderPorts();
RetrieveModuleBodyPorts();
}
// Writes all port names that match the predicate to the output stream,
// under the specified heading comment
void EmitNonAnsiPortList(
std::ostream &output, absl::string_view heading,
const std::function<bool(const Port &)> &pred) const;
// Writes port connections to all ports to the output stream, under the
// specified heading comment
void EmitPortConnections(std::ostream &output,
absl::string_view instance_name,
absl::string_view header,
const std::function<bool(const Port &)> &pred,
const Template *tmpl) const;
// Writes declarations of ports that fulfill the given predicate to the
// output stream
void EmitPortDeclarations(
std::ostream &output, PortDeclStyle style,
const std::function<bool(const Port &)> &pred) const;
// Writes wire declarations of undeclared output ports to the output stream,
// with the provided span defining which existing wires were autogenerated
void EmitUndeclaredWireDeclarations(std::ostream &output,
absl::string_view auto_span) const;
// Writes reg declarations of unconnected output ports to the output stream,
// with the provided span defining which existing regs were autogenerated
void EmitUnconnectedOutputRegDeclarations(
std::ostream &output, absl::string_view auto_span) const;
// Calls the closure on each port and the name of the port that should be
// connected to it. If a template is given, the connected port name is taken
// from the template, otherwise it's the same as the port name.
void GenerateConnections(
absl::string_view instance_name, const Template *tmpl,
const std::function<void(const Port &, const Connection &)> &fun) const;
// Set an existing port's connection, or create a new port with the given
// name, direction, and connection
void AddGeneratedConnection(
const std::string &port_name, Port::Direction direction,
const ConnectedInstance &connected,
const std::vector<Dimension> &packed_dimensions,
const std::vector<Dimension> &unpacked_dimensions);
// Sort ports by location in the source
void SortPortsByLocation();
// Gets all AUTO_TEMPLATEs from the module
void RetrieveAutoTemplates();
// Gets all dependencies of the module (modules instantiated within it)
void RetrieveDependencies(
const absl::node_hash_map<absl::string_view, Module> &modules);
// Retrieves the matching template from a typename -> template map
const Template *GetAutoTemplate(
absl::string_view type_id, absl::string_view instance_name,
absl::string_view::const_iterator instance_it) const;
// Returns true if the module depends on (uses) a given module
bool DependsOn(const Module *module) const {
absl::flat_hash_set<const Module *> visited;
return DependsOn(module, &visited);
}
// Returns true if any ports fulfill the given predicate
bool AnyPorts(const std::function<bool(const Port &)> &pred) {
return std::find_if(ports_.begin(), ports_.end(), pred) != ports_.end();
}
// Calls the given function on each port
void ForEachPort(const std::function<void(Port &)> &fun) {
std::for_each(ports_.begin(), ports_.end(), fun);
}
// Erase all ports that fulfill the given predicate
void ErasePortsIf(const std::function<bool(const Port &)> &pred) {
const auto it = std::remove_if(ports_.begin(), ports_.end(), pred);
ports_.erase(it, ports_.end());
}
// Returns the Symbol representing this module
const verible::Symbol &Symbol() const { return symbol_; }
// Returns the module name
absl::string_view Name() const { return name_; }
private:
// Gets ports from the header of the module
void RetrieveModuleHeaderPorts();
// Gets ports from the body of the module
void RetrieveModuleBodyPorts();
// Store the given port in the internal vector
void PutDeclaredPort(const SyntaxTreeNode &port_node);
// Recurses into dependencies to check if we depend on a given module.
// Stores visited modules in a set to avoid infinite loops. For big
// dependency graphs one should build a proper graph and do a
// topological sort. However, these dependencies (and the dependent) are all
// from a single file, and usually there is only one module per file. This
// should be fast enough for unusual cases where there are multiple modules
// in a single file.
bool DependsOn(const Module *module,
absl::flat_hash_set<const Module *> *visited) const;
// The symbol that represents this module
const verible::Symbol &symbol_;
// The name of this module
const absl::string_view name_;
// This module's ports
std::vector<Port> ports_;
// New wires to emit (if not already defined)
std::vector<Wire> wires_to_generate_;
// This module's direct dependencies
absl::flat_hash_set<const Module *> dependencies_;
// This module's AUTO_TEMPLATEs
Template::Map templates_;
};
AutoExpander(const TextStructureView &text_structure,
SymbolTableHandler *symbol_table_handler)
: text_structure_(text_structure),
symbol_table_handler_(symbol_table_handler) {
expand_span_ = text_structure_.Contents();
}
AutoExpander(const TextStructureView &text_structure,
SymbolTableHandler *symbol_table_handler,
Interval<size_t> line_range)
: AutoExpander(text_structure, symbol_table_handler) {
size_t min = line_range.min < text_structure.Lines().size()
? line_range.min
: text_structure.Lines().size() - 1;
size_t max = line_range.max < text_structure.Lines().size()
? line_range.max
: text_structure.Lines().size() - 1;
const auto begin = text_structure.Lines()[min].begin();
const auto end = text_structure.Lines()[max].end();
const size_t length = static_cast<size_t>(std::distance(begin, end));
expand_span_ = absl::string_view(begin, length);
}
AutoExpander(const TextStructureView &text_structure,
SymbolTableHandler *symbol_table_handler,
const absl::flat_hash_set<AutoKind> &allowed_autos)
: AutoExpander(text_structure, symbol_table_handler) {
allowed_autos_ = allowed_autos;
}
// Retrieves port names from a module declared before the given location
absl::flat_hash_set<absl::string_view> GetPortsListedBefore(
const Symbol &module, absl::string_view::const_iterator it) const;
// Retrieves port names from a module instance connected before the given
// location
absl::flat_hash_set<absl::string_view> GetPortsConnectedBefore(
const Symbol &instance, absl::string_view::const_iterator it) const;
// Expands AUTOARG for the given module
std::optional<Expansion> ExpandAutoarg(const Module &module) const;
// Expands AUTOINST for the given module instance
std::optional<Expansion> ExpandAutoinst(Module *module,
const Symbol &instance,
absl::string_view type_id);
// Expands AUTO<port-direction/data-type> for the given module
// Limitation: this only detects ports from AUTOINST. This limitation is also
// present in the original Emacs Verilog-mode.
std::optional<Expansion> ExpandAutoDeclarations(
const Module &module, Match match, absl::string_view description,
const std::function<void(const Module &, std::ostream &)> &emit) const;
// Expands AUTOINPUT/AUTOINOUT/AUTOOUTPUT for the given module
std::optional<Expansion> ExpandAutoPorts(Module *module,
std::optional<Match> match,
Port::Direction direction) const;
// Expands AUTOWIRE for the given module
std::optional<Expansion> ExpandAutowire(const Module &module) const;
// Expands AUTOREG for the given module
std::optional<Expansion> ExpandAutoreg(const Module &module) const;
// Expands all AUTOs in the buffer
std::vector<Expansion> Expand();
// Find kinds of AUTO used in the expand span
absl::flat_hash_set<AutoKind> FindAutoKinds();
private:
// Matches the given regex and erases ports from the module that are in the
// match span
std::optional<Match> FindMatchAndErasePorts(AutoExpander::Module *module,
AutoKind kind, const RE2 &re);
// Finds the span that should be replaced in the symbol (from the start of
// the comment span to the end of the symbol span. Used by AUTOARG and
// AUTOINST)
std::optional<absl::string_view> FindSpanToReplace(
const Symbol &symbol, absl::string_view auto_span) const;
// Checks if the given AUTO kind should be expanded
bool ShouldExpand(const AutoKind kind) const {
return allowed_autos_.empty() || allowed_autos_.contains(kind);
}
// Span in which expansions are allowed
absl::string_view expand_span_;
// Kinds of AUTOs that can be expanded (all if this set is empty)
absl::flat_hash_set<AutoKind> allowed_autos_;
// Text structure of the buffer to expand AUTOs in
const TextStructureView &text_structure_;
// Symbol table wrapper for the language server
SymbolTableHandler *symbol_table_handler_;
// Gathered module information (module name -> module info)
absl::node_hash_map<absl::string_view, Module> modules_;
// Regex for finding any AUTOs
static const LazyRE2 auto_re_;
// Regex for finding AUTOARG comments
static const LazyRE2 autoarg_re_;
// Regex for finding AUTOINST comments
static const LazyRE2 autoinst_re_;
// Regexes for AUTO_TEMPLATE comments
static const LazyRE2 autotemplate_re_;
static const LazyRE2 autotemplate_type_re_;
static const LazyRE2 autotemplate_conn_re_;
// Regexes for AUTOINPUT/AUTOOUTPUT/AUTOINOUT/AUTOWIRE/AUTOREG comments
static const LazyRE2 autoinput_re_;
static const LazyRE2 autooutput_re_;
static const LazyRE2 autoinout_re_;
static const LazyRE2 autowire_re_;
static const LazyRE2 autoreg_re_;
};
const LazyRE2 AutoExpander::auto_re_{
R"(/\*\s*(AUTOARG|AUTOINST|AUTOINPUT|AUTOINOUT|AUTOOUTPUT|AUTOWIRE|AUTOREG)\s*\*/)"};
const LazyRE2 AutoExpander::autoarg_re_{R"((/\*\s*AUTOARG\s*\*/))"};
const LazyRE2 AutoExpander::autoinst_re_{R"((/\*\s*AUTOINST\s*\*/))"};
// AUTO_TEMPLATE regex breakdown:
// The entire expression is wrapped in () so the first capturing group is the
// entire match.
// /\* – start of comment
// (?:\s*\S+\s+AUTO_TEMPLATE\s*\n)* – optional other AUTO_TEMPLATE types, end
// with newline
// \s*\S+\s+AUTO_TEMPLATE – at least one AUTO_TEMPLATE is required
// \s*(?:"([^"])*")? – optional instance name regex
// \s*\(?:[\s\S]*?\); – parens with port connections
// \s*\*/ – end of comment
const LazyRE2 AutoExpander::autotemplate_re_{
R"((/\*(?:\s*\S+\s+AUTO_TEMPLATE\s*\n)*\s*\S+\s+AUTO_TEMPLATE\s*(?:"([^"]*)\")?\s*\([\s\S]*?\);\s*\*/))"};
// AUTO_TEMPLATE type regex: the first capturing group is the instance type
const LazyRE2 AutoExpander::autotemplate_type_re_{R"((\S+)\s+AUTO_TEMPLATE)"};
// AUTO_TEMPLATE connection regex breakdown:
// \.\s* – starts with a dot
// ([^\s(]+?) – first group, at least one character other than whitespace or
// opening paren
// \s*\(\s* – optional whitespace, opening paren, optional whitespace again
// ([^\s(]+?) – second group, same as the first one
// \s*(\[\])? – optional third group, capturing '[]'
// \s*\)* – optional whitespace, closing paren
const LazyRE2 AutoExpander::autotemplate_conn_re_{
R"(\.\s*([^\s(]+?)\s*\(\s*([^\s(]+?)\s*(\[\])?\s*\))"};
// AUTOINPUT/OUTPUT/INOUT/WIRE/REG regex breakdown:
// The entire expression is wrapped in () so the first capturing group is the
// entire match.
// (/\*\s* ... \s*\*/\s*?\n) – starting comment
// (?:\s*//.*\n)? – optional starting comment
// ("Beginning of automatic...")
// (?: ... )? – an optional non-capturing group:
// [\s\S]*? – any text (usually port
// declarations)
// [^\S\r\n]*// End of automatics.*\n – ended by an "End of automatics"
// comment
#define MAKE_AUTODECL_REGEX(decl_kind) \
R"(((/\*\s*AUTO)" decl_kind \
R"(\s*\*/\s*?)(?:\s*//.*)?(?:[\s\S]*?[^\S\r\n]*// End of automatics.*)?))"
const LazyRE2 AutoExpander::autoinput_re_{MAKE_AUTODECL_REGEX("INPUT")};
const LazyRE2 AutoExpander::autoinout_re_{MAKE_AUTODECL_REGEX("INOUT")};
const LazyRE2 AutoExpander::autooutput_re_{MAKE_AUTODECL_REGEX("OUTPUT")};
const LazyRE2 AutoExpander::autowire_re_{MAKE_AUTODECL_REGEX("WIRE")};
const LazyRE2 AutoExpander::autoreg_re_{MAKE_AUTODECL_REGEX("REG")};
using Dimension = AutoExpander::Dimension;
using DimensionRange = AutoExpander::DimensionRange;
// Fallback for the case of comparing two dimensions if there is no obvious
// maximum. Simply returns the first given dimension.
template <typename T, typename U>
static Dimension MaxDimension(const T first, const U second) {
return first;
}
// Returns the greater of the two given dimensions.
template <>
Dimension MaxDimension(const size_t first, const size_t second) {
return std::max(first, second);
}
// Returns a range that can fit the two given dimensions.
template <>
Dimension MaxDimension(const DimensionRange first,
const DimensionRange second) {
int64_t max = std::max(std::max(first.msb, first.lsb),
std::max(second.msb, second.lsb));
int64_t min = std::min(std::min(first.msb, first.lsb),
std::min(second.msb, second.lsb));
if (first.msb >= first.lsb) {
return DimensionRange{.msb = max, .lsb = min};
}
return DimensionRange{.msb = min, .lsb = max};
}
// Converts the first dimension to a DimensionRange, and then returns the
// maximum of it and the given range.
template <>
Dimension MaxDimension(const size_t first, const DimensionRange second) {
return MaxDimension(
DimensionRange{.msb = static_cast<int64_t>(first) - 1, .lsb = 0}, second);
}
// Converts the second dimension to a DimensionRange, and then returns the
// maximum of it and the given range.
template <>
Dimension MaxDimension(const DimensionRange first, const size_t second) {
return MaxDimension(
first, DimensionRange{.msb = static_cast<int64_t>(second) - 1, .lsb = 0});
}
std::vector<Dimension> AutoExpander::MaxDimensions(
const std::vector<Dimension> &first, const std::vector<Dimension> &second) {
if (first.empty() && second.size() == 1) return second;
if (second.empty() && first.size() == 1) return first;
if (first.size() != second.size()) LOG(ERROR) << "Mismatched dimensions";
std::vector<Dimension> dims;
auto it1 = first.begin(), it2 = second.begin();
while (it1 != first.end() && it2 != second.end()) {
const auto dims1 = *it1, dims2 = *it2;
std::visit(
[&](const auto d1) {
std::visit(
[&](const auto d2) { dims.push_back(MaxDimension(d1, d2)); },
dims2);
},
dims1);
++it1;
++it2;
}
return dims;
}
std::ostream &operator<<(std::ostream &os, const DimensionRange range) {
os << range.msb << ":" << range.lsb;
return os;
}
std::ostream &operator<<(std::ostream &os, const Dimension dim) {
std::visit([&os](auto &&arg) { os << '[' << arg << ']'; }, dim);
return os;
}
void AutoExpander::Net::EmitIdWithDimensions(std::ostream &output) const {
if (!packed_dimensions.empty()) {
for (const Dimension &dimension : packed_dimensions) {
output << dimension;
}
output << ' ';
}
output << name;
for (const Dimension &dimension : unpacked_dimensions) {
output << dimension;
}
}
void AutoExpander::Port::EmitDirection(std::ostream &output) const {
switch (direction) {
case Port::Direction::kInput:
output << "input ";
break;
case Port::Direction::kInout:
output << "inout ";
break;
case Port::Direction::kOutput:
output << "output ";
break;
default:
LOG(ERROR) << "Incorrect port direction";
break;
}
}
void AutoExpander::Port::EmitConnectionComment(std::ostream &output) const {
if (conn_inst.empty()) return;
const auto &instance = conn_inst[0].instance;
if (!instance) return;
const absl::string_view type = conn_inst[0].type;
switch (direction) {
case Direction::kInput:
output << " // To " << *instance << " of " << type;
break;
case Direction::kInout:
output << " // To/From " << *instance << " of " << type;
break;
case Direction::kOutput:
output << " // From " << *instance << " of " << type;
break;
default:
LOG(ERROR) << "Incorrect port direction";
return;
}
if (conn_inst.size() > 1) output << ", ...";
// TODO: Print as many instance names as we can without going against the
// formatter?
}
void AutoExpander::Wire::EmitConnectionComment(std::ostream &output) const {
if (conn_inst.empty()) return;
const auto &instance = conn_inst[0].instance;
if (!instance) return;
output << " // To/From " << *instance << " of " << conn_inst[0].type;
if (conn_inst.size() > 1) output << ", ..";
}
void AutoExpander::Module::EmitNonAnsiPortList(
std::ostream &output, const absl::string_view heading,
const std::function<bool(const Port &)> &pred) const {
bool first = true;
for (const Port &port : ports_) {
if (!pred(port)) continue;
if (first) {
if (output.tellp() != 0) output << ',';
output << '\n' << "// " << heading << '\n';
first = false;
} else {
output << ',';
}
output << port.name;
}
}
void AutoExpander::Module::EmitPortConnections(
std::ostream &output, const absl::string_view instance_name,
const absl::string_view header,
const std::function<bool(const Port &)> &pred, const Template *tmpl) const {
bool first = true;
GenerateConnections(
instance_name, tmpl, [&](const Port &port, const Connection &connected) {
if (!pred(port)) return;
if (first) {
if (output.tellp() != 0) output << ',';
output << '\n' << "// " << header;
first = false;
} else {
output << ',';
}
output << '\n' << '.' << port.name << '(' << connected.port_name;
if (!connected.emit_dimensions) {
output << ')';
return;
}
if (port.packed_dimensions.size() > 1 ||
!port.unpacked_dimensions.empty()) {
output << "/*";
for (const Dimension &dimension : port.packed_dimensions) {
output << dimension;
}
if (!port.unpacked_dimensions.empty()) {
output << '.';
for (const Dimension &dimension : port.unpacked_dimensions) {
output << dimension;
}
}
output << "*/";
} else if (port.packed_dimensions.size() == 1) {
output << port.packed_dimensions[0];
}
output << ')';
});
}
// Checks if two string spans are overlapping
bool SpansOverlapping(const absl::string_view first,
const absl::string_view second) {
return first.end() > second.begin() && first.begin() < second.end();
}
void AutoExpander::Module::EmitUndeclaredWireDeclarations(
std::ostream &output, const absl::string_view auto_span) const {
absl::flat_hash_set<absl::string_view> declared_wires;
for (const auto ® : FindAllNetVariables(symbol_)) {
const SyntaxTreeLeaf *const net_name_leaf =
GetNameLeafOfNetVariable(*reg.match);
const absl::string_view net_name = net_name_leaf->get().text();
if (!SpansOverlapping(net_name, auto_span)) {
declared_wires.insert(net_name);
}
}
for (const Port &port : ports_) {
if (port.direction != Port::Direction::kInput &&
port.declaration == Port::Declaration::kUndeclared &&
port.IsConnected() && !declared_wires.contains(port.name)) {
output << "wire ";
port.EmitIdWithDimensions(output);
output << ';';
port.EmitConnectionComment(output);
output << '\n';
}
}
for (const Wire &wire : wires_to_generate_) {
output << "wire ";
wire.EmitIdWithDimensions(output);
output << ';';
wire.EmitConnectionComment(output);
output << '\n';
}
}
void AutoExpander::Module::EmitUnconnectedOutputRegDeclarations(
std::ostream &output, const absl::string_view auto_span) const {
absl::flat_hash_set<absl::string_view> declared_regs;
for (const auto ® : FindAllRegisterVariables(symbol_)) {
const SyntaxTreeLeaf *const reg_name_leaf =
GetNameLeafOfRegisterVariable(*reg.match);
const absl::string_view reg_name = reg_name_leaf->get().text();
if (!SpansOverlapping(reg_name, auto_span)) {
declared_regs.insert(reg_name);
}
}
for (const Port &port : ports_) {
if (port.direction == Port::Direction::kOutput &&
port.declaration == Port::Declaration::kDeclared &&
!port.IsConnected() && !declared_regs.contains(port.name)) {
output << "reg ";
port.EmitIdWithDimensions(output);
output << ";\n";
}
}
}
void AutoExpander::Module::GenerateConnections(
absl::string_view instance_name, const Template *tmpl,
const std::function<void(const Port &, const Connection &)> &fun) const {
for (const Port &port : ports_) {
Connection connected{.port_name = port.name, .emit_dimensions = true};
if (tmpl) {
const auto it = tmpl->connections.find(port.name);
if (it != tmpl->connections.end()) connected = it->second;
}
size_t pos = connected.port_name.find('@');
while (pos != std::string::npos) {
connected.port_name.replace(pos, 1, instance_name.begin(),
instance_name.length());
pos = connected.port_name.find('@', pos);
}
fun(port, connected);
}
}
void AutoExpander::Module::AddGeneratedConnection(
const std::string &port_name, const Port::Direction direction,
const ConnectedInstance &connected,
const std::vector<Dimension> &packed_dimensions,
const std::vector<Dimension> &unpacked_dimensions) {
const auto name_matches = [&](const Net &net) {
return net.name == port_name;
};
const auto wire_it = std::find_if(wires_to_generate_.begin(),
wires_to_generate_.end(), name_matches);
// If there is already a wire with the same name, add the connection to it.
// This wire is a connection between multiple instances.
if (wire_it != wires_to_generate_.end()) {
wire_it->AddConnection(connected, packed_dimensions);
return;
}
const auto port_it = std::find_if(ports_.begin(), ports_.end(), name_matches);
// Else look for an existing port with this name. If there is one, and it has
// the same direction, reuse it. If its direction differs, convert it to a new
// wire.
if (port_it != ports_.end()) {
Port &port = *port_it;
if (port.direction == direction) {
port.AddConnection(connected, packed_dimensions);
} else {
wires_to_generate_.push_back(
{{.name = port_name,
.conn_inst = port.conn_inst,
.packed_dimensions = AutoExpander::MaxDimensions(
port.packed_dimensions, packed_dimensions),
.unpacked_dimensions = unpacked_dimensions}});
wires_to_generate_.back().AddConnection(connected, packed_dimensions);
ports_.erase(port_it, port_it + 1);
}
return;
}
// There are no wires or ports of the given name. Just make a new port.
ports_.push_back({
{port_name, {connected}, packed_dimensions, unpacked_dimensions},
direction,
Port::Declaration::kUndeclared,
nullptr,
});
}
void AutoExpander::Module::SortPortsByLocation() {
// Stable sort is needed here, as ports autogenerated via AUTOINPUT,
// AUTOOUTPUT, and AUTOINOUT get assigned one location, which is the start of
// the corresponding `AUTO` comment. Using unstable sort results in a random
// order of ports.
std::stable_sort(
ports_.begin(), ports_.end(),
[](const Port &left, const Port &right) { return left.it < right.it; });
}
void AutoExpander::Module::RetrieveAutoTemplates() {
absl::string_view autotmpl_search_span = StringSpanOfSymbol(symbol_);
absl::string_view autotmpl_span;
absl::string_view autotmpl_inst_name;
while (RE2::FindAndConsume(&autotmpl_search_span, *autotemplate_re_,
&autotmpl_span, &autotmpl_inst_name)) {
Template tmpl{.it = autotmpl_span.begin()};
if (!autotmpl_inst_name.empty()) {
tmpl.instance_name_re = std::make_shared<RE2>(autotmpl_inst_name);
if (!tmpl.instance_name_re->ok()) {
LOG(ERROR) << "Invalid regex in AUTO template: " << autotmpl_inst_name;
continue;
}
}
absl::string_view autotmpl_conn_search_span = autotmpl_span;
absl::string_view instance_port_name;
absl::string_view module_port_name;
absl::string_view dimensions;
while (RE2::FindAndConsume(&autotmpl_conn_search_span,
*autotemplate_conn_re_, &instance_port_name,
&module_port_name, &dimensions)) {
tmpl.connections.insert(
std::make_pair(instance_port_name,
Connection{.port_name = std::string(module_port_name),
.emit_dimensions = !dimensions.empty()}));
}
absl::string_view autotmpl_type_search_span = autotmpl_span;
absl::string_view instance_type_name;
while (RE2::FindAndConsume(&autotmpl_type_search_span,
*autotemplate_type_re_, &instance_type_name)) {
templates_[instance_type_name].push_back(tmpl);
}
}
}
void AutoExpander::Module::RetrieveDependencies(
const absl::node_hash_map<absl::string_view, Module> &modules) {
for (const auto &data : FindAllDataDeclarations(symbol_)) {
const verible::Symbol *const type_id_node =
GetTypeIdentifierFromDataDeclaration(*data.match);
// Some data declarations do not have a type id, ignore those
if (!type_id_node) continue;
const absl::string_view dependency_name = StringSpanOfSymbol(*type_id_node);
const auto it = modules.find(dependency_name);
if (it != modules.end()) {
dependencies_.insert(&it->second);
}
}
}
const AutoExpander::Template *AutoExpander::Module::GetAutoTemplate(
const absl::string_view type_id, const absl::string_view instance_name,
const absl::string_view::const_iterator instance_it) const {
const auto it = templates_.find(type_id);
if (it == templates_.end()) return nullptr;
const Template *matching_tmpl = nullptr;
// Linear search for the matching template (there should be very few
// templates per type, often just one)
for (const Template &tmpl : it->second) {
if (instance_it < tmpl.it) break;
if (tmpl.instance_name_re) {
if (!RE2::FullMatch(instance_name, *tmpl.instance_name_re)) continue;
}
matching_tmpl = &tmpl;
}
return matching_tmpl;
}
void AutoExpander::Module::EmitPortDeclarations(
std::ostream &output, const PortDeclStyle style,
const std::function<bool(const Port &)> &pred) const {
const auto end = std::find_if(ports_.crbegin(), ports_.crend(), pred).base();
for (auto it = ports_.cbegin(); it != end; it++) {
const Port &port = *it;
if (!pred(port)) continue;
port.EmitDirection(output);
port.EmitIdWithDimensions(output);
if (style == PortDeclStyle::kColonSeparator) {
output << ';';
} else if (style == PortDeclStyle::kCommaSeparator || it + 1 < end) {
output << ',';
}
port.EmitConnectionComment(output);
output << '\n';
}
}
void AutoExpander::Module::RetrieveModuleHeaderPorts() {
const auto module_ports = GetModulePortDeclarationList(symbol_);
if (!module_ports) return;
for (const SymbolPtr &port : module_ports->children()) {
if (port->Kind() == SymbolKind::kLeaf) continue;
const SyntaxTreeNode &port_node = SymbolCastToNode(*port);
const NodeEnum tag = NodeEnum(port_node.Tag().tag);
if (tag == NodeEnum::kPortDeclaration) {
PutDeclaredPort(port_node);
}
}
}
void AutoExpander::Module::RetrieveModuleBodyPorts() {
for (const auto &port : FindAllModulePortDeclarations(symbol_)) {
PutDeclaredPort(SymbolCastToNode(*port.match));
}
}
// Converts kDimensionScalar and kDimensionRange nodes to Dimensions. Parses
// them as integers or ranges if possible, falls back to a string span.
std::vector<AutoExpander::Dimension> GetDimensionsFromNodes(
const std::vector<TreeSearchMatch> &dimension_nodes) {
using Dimension = AutoExpander::Dimension;
std::vector<Dimension> dimensions;
dimensions.reserve(dimension_nodes.size());
for (auto &dimension : dimension_nodes) {
for (const auto &scalar :
SearchSyntaxTree(*dimension.match, NodekDimensionScalar())) {
size_t size;
const Symbol &scalar_value =
*SymbolCastToNode(*scalar.match).children()[1];
const absl::string_view span = StringSpanOfSymbol(scalar_value);
const bool result = absl::SimpleAtoi(span, &size);
dimensions.push_back(result ? Dimension{size} : Dimension{span});
}
for (const auto &range :
SearchSyntaxTree(*dimension.match, NodekDimensionRange())) {
const Symbol *left = GetDimensionRangeLeftBound(*range.match);
const Symbol *right = GetDimensionRangeRightBound(*range.match);
int64_t msb, lsb;
const bool left_result =
absl::SimpleAtoi(StringSpanOfSymbol(*left), &msb);
const bool right_result =
absl::SimpleAtoi(StringSpanOfSymbol(*right), &lsb);
if (left_result && right_result) {
dimensions.push_back(
AutoExpander::DimensionRange{.msb = msb, .lsb = lsb});
} else {
const absl::string_view left_span = StringSpanOfSymbol(*left);
const absl::string_view right_span = StringSpanOfSymbol(*right);
dimensions.push_back(absl::string_view{
left_span.begin(), static_cast<size_t>(std::distance(
left_span.begin(), right_span.end()))});
}
}
}
return dimensions;
}
void AutoExpander::Module::PutDeclaredPort(const SyntaxTreeNode &port_node) {
const NodeEnum tag = NodeEnum(port_node.Tag().tag);
const SyntaxTreeLeaf *const dir_leaf =
tag == NodeEnum::kPortDeclaration
? GetDirectionFromPortDeclaration(port_node)
: GetDirectionFromModulePortDeclaration(port_node);
const SyntaxTreeLeaf *const id_leaf =
tag == NodeEnum::kPortDeclaration
? GetIdentifierFromPortDeclaration(port_node)
: GetIdentifierFromModulePortDeclaration(port_node);
if (!dir_leaf || !id_leaf) return;
const absl::string_view dir_span = dir_leaf->get().text();
const std::string name{id_leaf->get().text()};
std::vector<Dimension> packed_dimensions =
GetDimensionsFromNodes(FindAllPackedDimensions(port_node));
std::vector<Dimension> unpacked_dimensions =