-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathverilog_preprocessor.c++
1238 lines (1111 loc) · 33.2 KB
/
verilog_preprocessor.c++
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
/* TODOS:
* - find constants in not base 12 that have implicit length - add 32 to front
* - convert multidim wire thing to use pure indicies
* - generate loops
* - add #(...) to defparam conversion
* - remove signed, arithmetic shifts?
* - use WireInfo in module reclaration
* also, make sure WireInfo handles spaces (or lack thereof) ...
* - fix module rewrite detector (input with space thing?)
* - output wire... put this, and others, like signed and input wire in a final touches
* pass. should simplify things.
* Lain
*/
#include <iostream>
#include <sstream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <cstring>
#include <cctype>
#include <deque>
#include <stack>
#include <math.h>
#include <stdexcept>
using namespace std;
class Macro {
public:
Macro(istream& is);
Macro(string name, const vector<string>& params, string body);
string getName() { return name; }
string expand(const vector<string>& args);
bool isEmptyMacro() { return body.size() == 0; }
private:
bool is_function_like;
vector<string> params;
string body;
string name;
};
class WireInfo {
public:
const string& getName() { return name; }
const string& getType() { return type; }
size_t getDimensionSize(size_t dim_number) {
auto dim_info = dimension_sizes.at(dim_number-1);
return dim_info.second - dim_info.first;
};
size_t getLowerBound(size_t dim_number) { return dimension_sizes.at(dim_number-1).first; }
size_t getUpperBound(size_t dim_number) { return dimension_sizes.at(dim_number-1).second; }
size_t getNumDimensions() { return dimension_sizes.size(); }
WireInfo()
: name()
, type()
, use_custom_firstdim_decl(false)
, custom_firstdim_decl()
, dimension_sizes() { }
string makeDeclaration();
static std::pair<bool,WireInfo> parseWire(string&);
private:
string name;
string type;
bool use_custom_firstdim_decl;
string custom_firstdim_decl;
vector<std::pair<size_t,size_t>> dimension_sizes;
};
void macro_expansion_pass(istream& is, ostream& os, const vector<string>& predef_macros);
void module_redeclaration_pass(istream& is, ostream& os);
void twodim_reduction_pass(istream& is, ostream& os);
void final_touches_pass(istream& is, ostream& os);
vector<string> parseParamList(istream& is);
vector<string> parseParamList(const string& params_string);
string readUntil(istream& from, const char* until, bool ignore_initial_whitespace);
vector<string> splitAndTrim(const string& s, char delim);
string& trim(string& str);
string trim(const string& str);
string skipToNextLineIfComment(char prev_char, char c, istream& is);
string generate_define(const string& params);
long mathEval(istream& expr);
long mathEval(const string& s) {
istringstream iss(s);
return mathEval(iss);
}
int main(int argc, char** argv) {
vector<string> predef_macros;
for (int i = 0; i < argc; ++i) {
if (strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 'D') {
predef_macros.push_back(argv[i]+2);
}
}
stringstream with_reduced_twodims;
{
stringstream with_redeclared_modules;
{
stringstream with_expanded_macros;
{
macro_expansion_pass(cin, with_expanded_macros, predef_macros);
}
module_redeclaration_pass(with_expanded_macros, with_redeclared_modules);
}
twodim_reduction_pass(with_redeclared_modules, with_reduced_twodims);
}
final_touches_pass(with_reduced_twodims,cout);
return 0;
}
class IfdefState {
public:
IfdefState() : in_disabled_ifdef_block(false), found_good_branch() {}
void enterIfdef() { found_good_branch.push(false); }
void exitIfdef() { found_good_branch.pop(); setInDisabledIfdefBlock(false); }
void setInDisabledIfdefBlock(bool b) { in_disabled_ifdef_block = b; }
bool getInDisabledIfdefBlock() { return in_disabled_ifdef_block; }
bool foundGoodBranchAlready() { return found_good_branch.top(); }
void setFoundGoodBranch(bool b) { found_good_branch.pop(); found_good_branch.push(b); }
private:
bool in_disabled_ifdef_block;
std::stack<bool> found_good_branch;
IfdefState(const IfdefState&) = delete;
IfdefState& operator=(const IfdefState&) = delete;
};
void macro_expansion_pass(istream& is, ostream& os, const vector<string>& predef_macros) {
unordered_map<string,Macro> name2macro;
for (
auto predef_macro_name = predef_macros.begin();
predef_macro_name != predef_macros.end();
++predef_macro_name
) {
name2macro.insert(make_pair(*predef_macro_name, Macro(*predef_macro_name, {}, "")));
os << "`define " << *predef_macro_name << "\n";
}
IfdefState ifdef_state{};
char prev_char = '\0';
while (true) {
int c = is.get();
if (is.eof()) {
break;
}
string comment_line = skipToNextLineIfComment(prev_char,c,is);
if (comment_line.size() > 0) {
if (!ifdef_state.getInDisabledIfdefBlock()) {
os << (char)c << comment_line;
}
c = is.get();
string gendefine_flag = "%%GENDEFINE%%";
if (comment_line.compare(0,gendefine_flag.size(),gendefine_flag) == 0) {
string generated_define = generate_define(
comment_line.substr(gendefine_flag.size())
);
istringstream generated_define_ss(generated_define);
Macro m(generated_define_ss);
name2macro.insert(make_pair(m.getName(),m));
// cerr << "\n`define " << generated_define;
// cerr << "generated `" << m.getName() << "'\n";
}
}
if (is.eof()) {
break;
}
if (c == '`') {
string directive = trim(readUntil(is, ":;-+/*%){}[] (\n", true)); // arg.. regexes
if (directive == "define" && !ifdef_state.getInDisabledIfdefBlock()) {
Macro m(is);
name2macro.insert(make_pair(m.getName(),m));
if (m.isEmptyMacro()) {
os << "`define " << m.getName() << '\n';
}
} else if (directive == "ifdef") {
ifdef_state.enterIfdef();
string test_name = trim(readUntil(is," \n",true));
if (name2macro.find(test_name) != name2macro.end()) {
// macro is defined
ifdef_state.setFoundGoodBranch(true);
ifdef_state.setInDisabledIfdefBlock(false);
} else {
ifdef_state.setInDisabledIfdefBlock(true);
}
} else if (directive == "elseif") {
string test_name = trim(readUntil(is," \n",true));
if (
! ifdef_state.foundGoodBranchAlready()
&& name2macro.find(test_name) != name2macro.end()) {
ifdef_state.setInDisabledIfdefBlock(false);
ifdef_state.setFoundGoodBranch(true);
} else {
ifdef_state.setInDisabledIfdefBlock(true);
}
} else if (directive == "else") {
if (ifdef_state.foundGoodBranchAlready()) {
ifdef_state.setInDisabledIfdefBlock(true);
} else {
ifdef_state.setInDisabledIfdefBlock(false);
ifdef_state.setFoundGoodBranch(true);
}
} else if (directive == "endif") {
ifdef_state.exitIfdef();
} else if (!ifdef_state.getInDisabledIfdefBlock()) {
auto lookup_result = name2macro.find(directive);
if (lookup_result == name2macro.end()) {
// string lines = readUntil(is,"\n",false);
// lines += is.get();
// lines += readUntil(is,"\n",false);
// lines += is.get();
// lines += readUntil(is,"\n",false);
// lines += is.get();
cerr
<< "macro \""<<directive<<"\" has not been defined\n"
// << "near " << lines << "\n"
;
exit(1);
} else {
vector<string> param_list;
if (is.peek() == '(') {
param_list = parseParamList(is);
} // leave empty in other cases
os << lookup_result->second.expand(param_list);
}
}
} else if (!ifdef_state.getInDisabledIfdefBlock()) {
os.put(c);
}
prev_char = c;
}
}
void module_redeclaration_pass(istream& is, ostream& os) {
int prev_char = ' ';
while (true) {
int c = is.get();
if (is.eof()) {
break;
}
string comment_line = skipToNextLineIfComment(prev_char,c,is);
if (comment_line.size() > 0) {
os.put(c);
c = is.get();
os << comment_line;
}
if (is.eof()) {
break;
}
if (c == 'm' && isspace(prev_char)) {
is.putback(c);
string module_token;
is >> module_token;
os << module_token;
if (module_token == "module") {
string module_name = readUntil(is, "(", false);
os << module_name;
vector<string> module_params = parseParamList(is);
vector<string> module_param_names;
vector<string> module_param_types;
os << '(';
bool needs_redecl = false;
for (auto param = module_params.begin(); param != module_params.end(); ++param) {
if (param->find("input ") == 0 || param->find("output ") == 0) {
needs_redecl = true;
break;
}
}
for (auto param = module_params.begin(); param != module_params.end(); ++param) {
string::size_type last_space_index = param->find_last_of(" ");
// (NOTE: whitespace is trimmed in parseParamList)
if (needs_redecl) {
string name = param->substr(last_space_index);
os << name;
module_param_names.push_back(name);
module_param_types.push_back(param->substr(0, last_space_index));
} else {
os << *param;
}
if ((param + 1) != module_params.end()) {
os << ",\n";
}
}
os << ')';
{
string rest_of_decl = readUntil(is,";",false);
os << rest_of_decl << (char)is.get() << '\n';
}
if (needs_redecl) {
for (size_t i = 0; i < module_params.size(); ++i) {
string::size_type position_of_reg = string::npos;
if (module_param_types[i].find("output") != string::npos
&& (position_of_reg = module_param_types[i].find("reg")) != string::npos) {
// the case of an output reg
string rest_of_type = module_param_types[i].substr(position_of_reg + 3);
os << "output" << rest_of_type << module_param_names[i] << ";\n";
os << "reg " << rest_of_type << module_param_names[i] << ";\n";
} else {
os << module_params[i] << ";\n";
}
}
}
}
} else {
os.put(c);
}
prev_char = c;
}
}
void twodim_reduction_pass_redecl(
istream& is, ostream& os, unordered_map<string,WireInfo>& name2size);
void twodim_reduction_pass_rewrite(
istream& is, ostream& os, unordered_map<string,WireInfo>& name2size);
void twodim_reduction_pass(istream& is, ostream& os) {
unordered_map<string,WireInfo> name2size;
stringstream with_redecl;
twodim_reduction_pass_redecl(is, with_redecl, name2size);
twodim_reduction_pass_rewrite(with_redecl, os, name2size);
}
void twodim_reduction_pass_redecl(
istream& is, ostream& os, unordered_map<string,WireInfo>& name2size) {
int prev_char = ' ';
while (true) {
int c = is.get();
if (is.eof()) {
break;
}
string comment_line = skipToNextLineIfComment(prev_char,c,is);
if (comment_line.size() > 0) {
os.put(c);
c = is.get();
os << comment_line;
}
if (is.eof()) {
break;
}
if ((c == 'r' || c == 'w') && isspace(prev_char)) {
is.putback(c);
string decl;
is >> decl;
if (decl == "reg" || decl == "wire") {
decl += readUntil(is, ";", false);
trim(decl);
bool success = false;
WireInfo wire_info;
std::tie(success,wire_info) = WireInfo::parseWire(decl);
if (success && wire_info.getNumDimensions() > 1) {
is.get(); // consume ';'
name2size.insert(std::make_pair(wire_info.getName(),wire_info));
os << wire_info.makeDeclaration();
} else {
os << decl;
}
} else {
os << decl;
}
} else {
os.put(c);
}
prev_char = c;
}
// cerr << "found twodims:\n";
// for (auto twodim = name2size.begin(); twodim != name2size.end(); ++twodim) {
// cerr << "name="<<twodim->first<<" range="<<twodim->second.first<<"-"<<twodim->second.second<<"\n";
// }
}
void twodim_reduction_pass_rewrite(
istream& is,
ostream& os,
unordered_map<string,WireInfo>& name2size
) {
unordered_multimap<size_t,string> length2name;
size_t longest_name = 2;
for (
auto name_and_size = name2size.begin();
name_and_size != name2size.end();
++name_and_size
) {
length2name.insert(make_pair(name_and_size->first.size(),name_and_size->first));
if (name_and_size->first.size() > longest_name) {
longest_name = name_and_size->first.size();
}
}
deque<char> last_few_chars;
bool flush_buffer = false;
while (true) {
while (last_few_chars.size() < longest_name) {
last_few_chars.push_back(is.get());
if (is.eof()) {
last_few_chars.pop_back();
break;
}
}
if (!is.eof()) {
string comment_line = skipToNextLineIfComment(last_few_chars[0],last_few_chars[1],is);
if (comment_line.size() > 0) {
for (size_t i = 0; i < comment_line.size(); ++i) {
last_few_chars.push_back(comment_line[i]);
}
flush_buffer = true;
goto continue_and_ouput;
}
}
if (is.eof()) {
// flush buffer & exit
while (!last_few_chars.empty()) {
os.put(last_few_chars.front());
last_few_chars.pop_front();
}
break;
}
// see if the last n chars match a declared twodim (of length n)
{
string found_match = "";
// cerr << "comparing with `" << last_few_chars << "'\n";
for (size_t i = 1; i <= longest_name; ++i) { // must iterate from smallest to largest
auto range = length2name.equal_range(i);
if (range.first != length2name.end()) {
// have entries of this size
// cerr << "looking at twodims of size "<< i << '\n';
for (auto l2name_iter = range.first; l2name_iter != range.second; ++l2name_iter) {
string& name = l2name_iter->second;
// cerr << "\tlooking at `" << name << "'\n";
bool found_divergence = false;
auto last_char = last_few_chars.rbegin();
for (
auto char_in_name = name.rbegin();
char_in_name != name.rend() && last_char != last_few_chars.rend();
++char_in_name, ++last_char
) {
if (*char_in_name != *last_char) {
found_divergence = true;
break;
}
}
if (!found_divergence) {
found_match = name;
// cerr << name << " matches\n";
}
}
}
}
// sub in the match
if (found_match.size() > 0) {
string next_chars;
while (isspace(is.peek())) {
next_chars += is.get();
}
if (is.peek() == '[') {
is.get(); // consume '['
stringstream new_suffix;
string inside_brackets = readUntil(is,"]",false);
istringstream inside_brackets_ss(inside_brackets);
int evaluated_insides;
bool good = false;
try {
evaluated_insides = mathEval(inside_brackets_ss);
good = true;
} catch (const std::invalid_argument&) {
} catch (const std::out_of_range&) {
}
if (!good) {
last_few_chars.push_back('[');
for (size_t i = 0; i < inside_brackets.size(); ++i) {
last_few_chars.push_back(inside_brackets[i]);
}
flush_buffer = true;
goto continue_and_ouput;
}
new_suffix << "_" << evaluated_insides << next_chars;
is.get(); // consume ']';
while (true) {
char c = new_suffix.get();
if (new_suffix.eof()) {break;}
last_few_chars.push_back(c);
}
flush_buffer = true;
} else {
// didn't find a use. Shove it all back in
for (auto next_char = next_chars.rbegin(); next_char != next_chars.rend(); ++next_char) {
is.putback(*next_char);
}
}
}
}
continue_and_ouput:
while (
last_few_chars.size() >= longest_name
|| (flush_buffer && !last_few_chars.empty())
) {
os.put(last_few_chars.front());
// cerr.put(last_few_chars.front());
last_few_chars.pop_front();
}
flush_buffer = false;
}
}
vector<std::pair<string,string>> ft_strings_to_find {
{" signed ", " "},
{"output wire", "output"},
{"input wire", "input"},
{"'h", "32'h"},
};
void final_touches_pass(istream& is, ostream& os) {
size_t buffer_size = 0;
unordered_multimap<size_t,string> length2name;
for (
auto string_to_find = ft_strings_to_find.begin();
string_to_find != ft_strings_to_find.end();
++string_to_find
) {
length2name.insert(make_pair(string_to_find->first.size(),string_to_find->first));
if (string_to_find->first.size() > buffer_size) {
buffer_size = string_to_find->first.size();
}
}
deque<char> last_few_chars;
bool flush_buffer = false;
while (true) {
while (last_few_chars.size() < buffer_size) {
last_few_chars.push_back(is.get());
if (is.eof()) {
last_few_chars.pop_back();
break;
}
}
if (!is.eof()) {
string comment_line = skipToNextLineIfComment(last_few_chars[0],last_few_chars[1],is);
if (comment_line.size() > 0) {
for (size_t i = 0; i < comment_line.size(); ++i) {
last_few_chars.push_back(comment_line[i]);
}
flush_buffer = true;
goto continue_and_ouput;
}
}
if (is.eof()) {
// flush buffer & exit
while (!last_few_chars.empty()) {
os.put(last_few_chars.front());
last_few_chars.pop_front();
}
break;
}
// see if the last n chars match a declared twodim (of length n)
{
string found_match = "";
// cerr << "comparing with `" << last_few_chars << "'\n";
for (size_t i = 1; i <= buffer_size; ++i) { // must iterate from smallest to largest
auto range = length2name.equal_range(i);
if (range.first != length2name.end()) {
// have entries of this size
// cerr << "looking at twodims of size "<< i << '\n';
for (auto l2name_iter = range.first; l2name_iter != range.second; ++l2name_iter) {
string& name = l2name_iter->second;
// cerr << "\tlooking at `" << name << "'\n";
bool found_divergence = false;
auto last_char = last_few_chars.rbegin();
for (
auto char_in_name = name.rbegin();
char_in_name != name.rend() && last_char != last_few_chars.rend();
++char_in_name, ++last_char
) {
if (*char_in_name != *last_char) {
found_divergence = true;
break;
}
}
if (!found_divergence) {
found_match = name;
// cerr << name << " matches\n";
}
}
}
}
string output_str = "";
if (found_match == " signed ") {
output_str = " "; // eat it
} else if (found_match == "output wire") {
output_str = "output";
} else if (found_match == "input wire") {
output_str = "input";
}
if (output_str.size() > 0) {
// cerr << "found: " << found_match << " replacing with: " << output_str << "\n";
for (size_t i = 0; i < found_match.size(); ++i) {
last_few_chars.pop_back();
}
for (size_t i = 0; i < output_str.size(); ++i) {
last_few_chars.push_back(output_str[i]);
}
}
}
continue_and_ouput:
while (
last_few_chars.size() >= buffer_size
|| (flush_buffer && !last_few_chars.empty())
) {
os.put(last_few_chars.front());
// cerr.put(last_few_chars.front());
last_few_chars.pop_front();
}
flush_buffer = false;
}
}
Macro::Macro(string name_, const vector<string>& params_, string body_)
: is_function_like(params_.size() != 0)
, params(params_)
, body(body_)
, name(name_) {
}
Macro::Macro(istream& is)
: is_function_like(false)
, params()
, body()
, name() {
name = trim(readUntil(is, "\n (", true));
char next_char = is.get();
while(next_char == ' ') {next_char = is.get();}
is.putback(next_char);
if (next_char == '(') {
// if the next char is a '(' then it is a function-like
is_function_like = true;
} else {
// case of siple macro
is_function_like = false;
}
if (is_function_like) {
params = parseParamList(is);
}
bool found_backslash = false;
string line;
while (true) {
line += readUntil(is,"\\\n", false);
if (is.get() == '\\') {
found_backslash = true;
} else {
line += '\n';
body += line;
line.clear();
if (!found_backslash) {
break;
}
found_backslash = false;
}
}
trim(body);
// cerr
// << "found definition of macro `"<<name<<"'\n"
// << "params = "
// ;
// for (auto& param : params) {
// cerr << param << " ,";
// }
// cerr << "$\nbody = "<<body<<"\n";
}
string Macro::expand(const vector<string>& args) {
if (args.size() != params.size()) {
cerr <<
"num given args ("<<args.size()<<") and expected params ("<<params.size()<<")"
" differ for macro \""<<name<<"\"\n";
exit(1);
}
string expanded_body = body; // copy the unexpanded body;
for (size_t i = 0; i < params.size(); ++i) {
size_t pos = 0;
while ((pos = expanded_body.find(params[i], pos)) != std::string::npos) {
expanded_body.replace(pos, params[i].length(), args[i]);
pos += args[i].length();
}
}
return expanded_body;
}
string WireInfo::makeDeclaration() {
string onedim_base;
{
ostringstream onedim_builder;
onedim_builder << ( (trim(getType()) == "input wire") ? "input" : getType() ) << " [";
if (use_custom_firstdim_decl) {
onedim_builder << custom_firstdim_decl;
} else {
onedim_builder << getUpperBound(1) << ":" << getLowerBound(1);
}
onedim_builder << "] " << getName();
onedim_base = onedim_builder.str();
}
if (getNumDimensions() > 1) {
ostringstream builder;
for (size_t i = getLowerBound(2); i <= getUpperBound(2); ++i) {
builder << onedim_base << "_" << i << ";\n";
}
return builder.str();
} else {
return onedim_base;
}
}
std::pair<size_t,size_t> parseVectorDeclation(const string& decl) {
pair<size_t,size_t> result;
istringstream second_dim_decl(
trim(decl)
);
result.first = mathEval(readUntil(second_dim_decl, ":", true));
second_dim_decl.get(); // consume ':'
result.second = mathEval(second_dim_decl);
return result;
}
std::pair<bool,WireInfo> WireInfo::parseWire(string& decl) {
// cerr << "parsing wire/reg: `" << decl << "'\n";
bool success = false;
WireInfo wire_info;
trim(decl);
vector<string::size_type> bracket_locations {};
while(true) {
size_t prev_location = 0;
if (bracket_locations.size() != 0) {
prev_location = bracket_locations.back();
}
string::size_type next_bracket_location = decl.find_first_of("[", prev_location + 1);
if (next_bracket_location == string::npos) {
break;
} else {
bracket_locations.push_back(next_bracket_location);
}
}
string::size_type end_of_type = decl.find_first_of(" [", 0);
if (end_of_type == string::npos) {
success = false;
goto skip_to_return;
}
wire_info.type = trim(decl.substr(0, end_of_type));
if (bracket_locations.size() == 0) {
// cerr << "is nodim\n";
wire_info.dimension_sizes.push_back(make_pair(0,0));
wire_info.name = trim(
decl.substr(
decl.find_last_of(" ]") + 1,
string::npos
)
);
success = false;
} else {
for (
auto bracket_location = bracket_locations.begin();
bracket_location != bracket_locations.end();
++bracket_location
) {
string dim_decl = decl.substr(
*bracket_location + 1,
decl.find_first_of("]",*bracket_location) - (*bracket_location + 1)
);
try {
std::pair<size_t,size_t> dim_pair = parseVectorDeclation(dim_decl);
if (dim_pair.first > dim_pair.second) {
std::swap(dim_pair.first, dim_pair.second);
}
wire_info.dimension_sizes.push_back(dim_pair);
} catch (std::invalid_argument& e) {
wire_info.use_custom_firstdim_decl = true;
wire_info.custom_firstdim_decl = dim_decl;
}
// cerr << "dim\n";
}
string::size_type first_closing_bracket = decl.find_first_of("]", 0);
string::size_type end_of_name = decl.find_first_of(" [", first_closing_bracket + 2);
wire_info.name = trim(
decl.substr(
first_closing_bracket + 1,
end_of_name - (first_closing_bracket + 1)
)
);
success = true;
}
skip_to_return:
// cerr
// << "parsed WireInfo = {\n"
// "\tname = \"" << wire_info.getName() << "\",\n"
// "\ttype = \"" << wire_info.getType() << "\",\n"
// "\tnum_dims = " << wire_info.getNumDimensions() << ",\n"
// ;
// for (size_t i = 1; i <= wire_info.getNumDimensions(); ++i) {
// cerr
// << "\tdimension["<<i<<"] = ["
// << wire_info.getLowerBound(i) << ':' << wire_info.getUpperBound(i)
// << "],\n";
// }
// cerr << "}\n";
return std::make_pair(success, wire_info);
}
vector<string> parseParamList(const string& params_string) {
istringstream is(trim(params_string));
return parseParamList(is);
}
vector<string> parseParamList(istream& is) {
char first_char;
is >> first_char;
if (first_char != '(') {
cerr << "param list doesn't start with a '(' ( is '"<<first_char<<"')\n";
exit(1);
}
string param_list = readUntil(is,")",true);
is.get(); // consume ')'
// cerr << "param_list=\"" << param_list << "\"\n";
return splitAndTrim(param_list, ',');
}
string readUntil(istream& from, const char* until, bool ignore_initial_whitespace) {
string result;
bool first_time = true;
bool newline_in_search_set = strchr(until,'\n');
while (true) {
char c;
if (first_time && ignore_initial_whitespace) {
from >> c;
} else {
c = from.get();
}
if (from.eof()) {
break;
}
if (strchr(until,c) != NULL || (newline_in_search_set && (c == '\r') ) ) {
// found a matching char.
if (c == '\r' && newline_in_search_set && from.peek() == '\n') {
// do nothing; leave the \n in the stream
} else {
from.putback(c);
}
break;
} else {
result += c;
}
first_time = false;
}
return result;
}
vector<string> splitAndTrim(const string& s, char delim) {
istringstream ss(s);
vector<string> result;
string token;
while (getline(ss, token, delim)) {
trim(token);
result.push_back(token);
}
return result;
}
string& trim(string& str) {
str.erase(str.find_last_not_of(" \n\r\t") + 1, string::npos);
str.erase(0, str.find_first_not_of(" \n\r\t"));
return str;
}
string trim(const string& str) {
string result = str;
return trim(result);
}
string skipToNextLineIfComment(char prev_char, char c, istream& is) {
if (prev_char == '/' && c == '/') {
return readUntil(is,"\n",false);
}
return "";
}
std::pair<size_t,size_t> parseRange(const vector<string>& params, size_t index1, size_t index2) {
std::pair<size_t,size_t> range;
try {
range.first = mathEval(params[index1]);
range.second = mathEval(params[index2]);
} catch (const std::invalid_argument& e) {
cerr
<< "bad GENDEFINE param "<<(index1+1)<<" or "<<(index2+1)<<": '" << params[index1]
<< "'' or '" << params[index2] << "'\n";
exit(1);
} catch (const std::out_of_range& e) {
cerr
<< "bad GENDEFINE param "<<(index1+1)<<" or "<<(index2+1)<<" (out of range): '" << params[index1]
<< "'' or '" << params[index2] << "'\n";
exit(1);
}
return range;
}
string parseAssignmentOp(const vector<string>& params, size_t index) {
if (params[index] == "nonblocking") {
return "<=";
} else if (params[index] == "blocking") {
return "=";
} else {
cerr
<< "bad GENDEFINE param #"<<(index+1)<<": `"<<params[index]
<<"' did you mean blocking or nonblocking?\n";
exit(1);
return "";
}
}
enum class GendefineType : size_t {
NONE = 0,
CHOOSE_TO,
CHOOSE_FROM,
ALWAYS_LIST,
MOD_OP
};
namespace std {
template<>
struct hash<GendefineType> {
size_t operator()(const GendefineType& gt) const {
return std::hash<size_t>()(static_cast<size_t>(gt));
}
};
}