Rethrow with "catch(...) throw;"
[yosys.git] / kernel / yosys.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/yosys.h"
21 #include "kernel/celltypes.h"
22
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif
27
28 #ifdef YOSYS_ENABLE_PLUGINS
29 # include <dlfcn.h>
30 #endif
31
32 #ifdef _WIN32
33 # include <windows.h>
34 # include <io.h>
35 #elif defined(__APPLE__)
36 # include <mach-o/dyld.h>
37 # include <unistd.h>
38 # include <dirent.h>
39 # include <sys/stat.h>
40 #else
41 # include <unistd.h>
42 # include <dirent.h>
43 # include <sys/types.h>
44 # include <sys/stat.h>
45 #endif
46
47 #include <limits.h>
48 #include <errno.h>
49
50 YOSYS_NAMESPACE_BEGIN
51
52 int autoidx = 1;
53 int yosys_xtrace = 0;
54 RTLIL::Design *yosys_design = NULL;
55 CellTypes yosys_celltypes;
56
57 #ifdef YOSYS_ENABLE_TCL
58 Tcl_Interp *yosys_tcl_interp = NULL;
59 #endif
60
61 bool memhasher_active = false;
62 uint32_t memhasher_rng = 123456;
63 std::vector<void*> memhasher_store;
64
65 void memhasher_on()
66 {
67 #ifdef __linux__
68 memhasher_rng += time(NULL) << 16 ^ getpid();
69 #endif
70 memhasher_store.resize(0x10000);
71 memhasher_active = true;
72 }
73
74 void memhasher_off()
75 {
76 for (auto p : memhasher_store)
77 if (p) free(p);
78 memhasher_store.clear();
79 memhasher_active = false;
80 }
81
82 void memhasher_do()
83 {
84 memhasher_rng ^= memhasher_rng << 13;
85 memhasher_rng ^= memhasher_rng >> 17;
86 memhasher_rng ^= memhasher_rng << 5;
87
88 int size, index = (memhasher_rng >> 4) & 0xffff;
89 switch (memhasher_rng & 7) {
90 case 0: size = 16; break;
91 case 1: size = 256; break;
92 case 2: size = 1024; break;
93 case 3: size = 4096; break;
94 default: size = 0;
95 }
96 if (index < 16) size *= 16;
97 memhasher_store[index] = realloc(memhasher_store[index], size);
98 }
99
100 std::string stringf(const char *fmt, ...)
101 {
102 std::string string;
103 va_list ap;
104
105 va_start(ap, fmt);
106 string = vstringf(fmt, ap);
107 va_end(ap);
108
109 return string;
110 }
111
112 std::string vstringf(const char *fmt, va_list ap)
113 {
114 std::string string;
115 char *str = NULL;
116
117 #ifdef _WIN32
118 int sz = 64, rc;
119 while (1) {
120 va_list apc;
121 va_copy(apc, ap);
122 str = (char*)realloc(str, sz);
123 rc = vsnprintf(str, sz, fmt, apc);
124 va_end(apc);
125 if (rc >= 0 && rc < sz)
126 break;
127 sz *= 2;
128 }
129 #else
130 if (vasprintf(&str, fmt, ap) < 0)
131 str = NULL;
132 #endif
133
134 if (str != NULL) {
135 string = str;
136 free(str);
137 }
138
139 return string;
140 }
141
142 int readsome(std::istream &f, char *s, int n)
143 {
144 int rc = f.readsome(s, n);
145
146 // f.readsome() sometimes returns 0 on a non-empty stream..
147 if (rc == 0) {
148 int c = f.get();
149 if (c != EOF) {
150 *s = c;
151 rc = 1;
152 }
153 }
154
155 return rc;
156 }
157
158 std::string next_token(std::string &text, const char *sep)
159 {
160 size_t pos_begin = text.find_first_not_of(sep);
161
162 if (pos_begin == std::string::npos)
163 pos_begin = text.size();
164
165 size_t pos_end = text.find_first_of(sep, pos_begin);
166
167 if (pos_end == std::string::npos)
168 pos_end = text.size();
169
170 std::string token = text.substr(pos_begin, pos_end-pos_begin);
171 text = text.substr(pos_end);
172 return token;
173 }
174
175 // this is very similar to fnmatch(). the exact rules used by this
176 // function are:
177 //
178 // ? matches any character except
179 // * matches any sequence of characters
180 // [...] matches any of the characters in the list
181 // [!..] matches any of the characters not in the list
182 //
183 // a backslash may be used to escape the next characters in the
184 // pattern. each special character can also simply match itself.
185 //
186 bool patmatch(const char *pattern, const char *string)
187 {
188 if (*pattern == 0)
189 return *string == 0;
190
191 if (*pattern == '\\') {
192 if (pattern[1] == string[0] && patmatch(pattern+2, string+1))
193 return true;
194 }
195
196 if (*pattern == '?') {
197 if (*string == 0)
198 return false;
199 return patmatch(pattern+1, string+1);
200 }
201
202 if (*pattern == '*') {
203 while (*string) {
204 if (patmatch(pattern+1, string++))
205 return true;
206 }
207 return pattern[1] == 0;
208 }
209
210 if (*pattern == '[') {
211 bool found_match = false;
212 bool inverted_list = pattern[1] == '!';
213 const char *p = pattern + (inverted_list ? 1 : 0);
214
215 while (*++p) {
216 if (*p == ']') {
217 if (found_match != inverted_list && patmatch(p+1, string+1))
218 return true;
219 break;
220 }
221
222 if (*p == '\\') {
223 if (*++p == *string)
224 found_match = true;
225 } else
226 if (*p == *string)
227 found_match = true;
228 }
229 }
230
231 if (*pattern == *string)
232 return patmatch(pattern+1, string+1);
233
234 return false;
235 }
236
237 int run_command(const std::string &command, std::function<void(const std::string&)> process_line)
238 {
239 if (!process_line)
240 return system(command.c_str());
241
242 FILE *f = popen(command.c_str(), "r");
243 if (f == nullptr)
244 return -1;
245
246 std::string line;
247 char logbuf[128];
248 while (fgets(logbuf, 128, f) != NULL) {
249 line += logbuf;
250 if (!line.empty() && line.back() == '\n')
251 process_line(line), line.clear();
252 }
253 if (!line.empty())
254 process_line(line);
255
256 int ret = pclose(f);
257 if (ret < 0)
258 return -1;
259 #ifdef _WIN32
260 return ret;
261 #else
262 return WEXITSTATUS(ret);
263 #endif
264 }
265
266 std::string make_temp_file(std::string template_str)
267 {
268 #ifdef _WIN32
269 if (template_str.rfind("/tmp/", 0) == 0) {
270 # ifdef __MINGW32__
271 char longpath[MAX_PATH + 1];
272 char shortpath[MAX_PATH + 1];
273 # else
274 WCHAR longpath[MAX_PATH + 1];
275 TCHAR shortpath[MAX_PATH + 1];
276 # endif
277 if (!GetTempPath(MAX_PATH+1, longpath))
278 log_error("GetTempPath() failed.\n");
279 if (!GetShortPathName(longpath, shortpath, MAX_PATH + 1))
280 log_error("GetShortPathName() failed.\n");
281 std::string path;
282 for (int i = 0; shortpath[i]; i++)
283 path += char(shortpath[i]);
284 template_str = stringf("%s\\%s", path.c_str(), template_str.c_str() + 5);
285 }
286
287 size_t pos = template_str.rfind("XXXXXX");
288 log_assert(pos != std::string::npos);
289
290 while (1) {
291 for (int i = 0; i < 6; i++) {
292 static std::string y = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
293 static uint32_t x = 314159265 ^ uint32_t(time(NULL));
294 x ^= x << 13, x ^= x >> 17, x ^= x << 5;
295 template_str[pos+i] = y[x % y.size()];
296 }
297 if (_access(template_str.c_str(), 0) != 0)
298 break;
299 }
300 #else
301 size_t pos = template_str.rfind("XXXXXX");
302 log_assert(pos != std::string::npos);
303
304 int suffixlen = GetSize(template_str) - pos - 6;
305
306 char *p = strdup(template_str.c_str());
307 close(mkstemps(p, suffixlen));
308 template_str = p;
309 free(p);
310 #endif
311
312 return template_str;
313 }
314
315 std::string make_temp_dir(std::string template_str)
316 {
317 #ifdef _WIN32
318 template_str = make_temp_file(template_str);
319 mkdir(template_str.c_str());
320 return template_str;
321 #else
322 # ifndef NDEBUG
323 size_t pos = template_str.rfind("XXXXXX");
324 log_assert(pos != std::string::npos);
325
326 int suffixlen = GetSize(template_str) - pos - 6;
327 log_assert(suffixlen == 0);
328 # endif
329
330 char *p = strdup(template_str.c_str());
331 p = mkdtemp(p);
332 log_assert(p != NULL);
333 template_str = p;
334 free(p);
335
336 return template_str;
337 #endif
338 }
339
340 #ifdef _WIN32
341 bool check_file_exists(std::string filename, bool)
342 {
343 return _access(filename.c_str(), 0) == 0;
344 }
345 #else
346 bool check_file_exists(std::string filename, bool is_exec)
347 {
348 return access(filename.c_str(), is_exec ? X_OK : F_OK) == 0;
349 }
350 #endif
351
352 void remove_directory(std::string dirname)
353 {
354 #ifdef _WIN32
355 run_command(stringf("rmdir /s /q \"%s\"", dirname.c_str()));
356 #else
357 struct stat stbuf;
358 struct dirent **namelist;
359 int n = scandir(dirname.c_str(), &namelist, nullptr, alphasort);
360 log_assert(n >= 0);
361 for (int i = 0; i < n; i++) {
362 if (strcmp(namelist[i]->d_name, ".") && strcmp(namelist[i]->d_name, "..")) {
363 std::string buffer = stringf("%s/%s", dirname.c_str(), namelist[i]->d_name);
364 if (!stat(buffer.c_str(), &stbuf) && S_ISREG(stbuf.st_mode)) {
365 remove(buffer.c_str());
366 } else
367 remove_directory(buffer);
368 }
369 free(namelist[i]);
370 }
371 free(namelist);
372 rmdir(dirname.c_str());
373 #endif
374 }
375
376 int GetSize(RTLIL::Wire *wire)
377 {
378 return wire->width;
379 }
380
381 void yosys_setup()
382 {
383 // if there are already IdString objects then we have a global initialization order bug
384 IdString empty_id;
385 log_assert(empty_id.index_ == 0);
386 IdString::get_reference(empty_id.index_);
387
388 Pass::init_register();
389 yosys_design = new RTLIL::Design;
390 yosys_celltypes.setup();
391 log_push();
392 }
393
394 void yosys_shutdown()
395 {
396 log_pop();
397
398 delete yosys_design;
399 yosys_design = NULL;
400
401 for (auto f : log_files)
402 if (f != stderr)
403 fclose(f);
404 log_errfile = NULL;
405 log_files.clear();
406
407 Pass::done_register();
408 yosys_celltypes.clear();
409
410 #ifdef YOSYS_ENABLE_TCL
411 if (yosys_tcl_interp != NULL) {
412 Tcl_DeleteInterp(yosys_tcl_interp);
413 Tcl_Finalize();
414 yosys_tcl_interp = NULL;
415 }
416 #endif
417
418 #ifdef YOSYS_ENABLE_PLUGINS
419 for (auto &it : loaded_plugins)
420 dlclose(it.second);
421
422 loaded_plugins.clear();
423 loaded_plugin_aliases.clear();
424 #endif
425
426 IdString empty_id;
427 IdString::put_reference(empty_id.index_);
428 }
429
430 RTLIL::IdString new_id(std::string file, int line, std::string func)
431 {
432 #ifdef _WIN32
433 size_t pos = file.find_last_of("/\\");
434 #else
435 size_t pos = file.find_last_of('/');
436 #endif
437 if (pos != std::string::npos)
438 file = file.substr(pos+1);
439
440 pos = func.find_last_of(':');
441 if (pos != std::string::npos)
442 func = func.substr(pos+1);
443
444 return stringf("$auto$%s:%d:%s$%d", file.c_str(), line, func.c_str(), autoidx++);
445 }
446
447 RTLIL::Design *yosys_get_design()
448 {
449 return yosys_design;
450 }
451
452 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
453 {
454 static char buffer[100];
455 std::string str = "\n";
456 if (recursion_counter > 1)
457 str += stringf("(%d) ", recursion_counter);
458 str += "yosys";
459 if (!design->selected_active_module.empty())
460 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
461 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
462 if (design->selected_active_module.empty())
463 str += "*";
464 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
465 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
466 str += "*";
467 }
468 snprintf(buffer, 100, "%s> ", str.c_str());
469 return buffer;
470 }
471
472 #ifdef YOSYS_ENABLE_TCL
473 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
474 {
475 std::vector<std::string> args;
476 for (int i = 1; i < argc; i++)
477 args.push_back(argv[i]);
478
479 if (args.size() >= 1 && args[0] == "-import") {
480 for (auto &it : pass_register) {
481 std::string tcl_command_name = it.first;
482 if (tcl_command_name == "proc")
483 tcl_command_name = "procs";
484 Tcl_CmdInfo info;
485 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
486 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
487 } else {
488 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
489 Tcl_Eval(interp, tcl_script.c_str());
490 }
491 }
492 return TCL_OK;
493 }
494
495 if (args.size() == 1) {
496 Pass::call(yosys_get_design(), args[0]);
497 return TCL_OK;
498 }
499
500 Pass::call(yosys_get_design(), args);
501 return TCL_OK;
502 }
503
504 extern Tcl_Interp *yosys_get_tcl_interp()
505 {
506 if (yosys_tcl_interp == NULL) {
507 yosys_tcl_interp = Tcl_CreateInterp();
508 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
509 }
510 return yosys_tcl_interp;
511 }
512
513 struct TclPass : public Pass {
514 TclPass() : Pass("tcl", "execute a TCL script file") { }
515 virtual void help() {
516 log("\n");
517 log(" tcl <filename>\n");
518 log("\n");
519 log("This command executes the tcl commands in the specified file.\n");
520 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
521 log("\n");
522 log("The tcl command 'yosys -import' can be used to import all yosys\n");
523 log("commands directly as tcl commands to the tcl shell. The yosys\n");
524 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
525 log("to avoid a name collision with the tcl builting command 'proc'.\n");
526 log("\n");
527 }
528 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
529 if (args.size() < 2)
530 log_cmd_error("Missing script file.\n");
531 if (args.size() > 2)
532 extra_args(args, 1, design, false);
533 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
534 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
535 }
536 } TclPass;
537 #endif
538
539 #if defined(__linux__)
540 std::string proc_self_dirname()
541 {
542 char path[PATH_MAX];
543 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
544 if (buflen < 0) {
545 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
546 }
547 while (buflen > 0 && path[buflen-1] != '/')
548 buflen--;
549 return std::string(path, buflen);
550 }
551 #elif defined(__APPLE__)
552 std::string proc_self_dirname()
553 {
554 char *path = NULL;
555 uint32_t buflen = 0;
556 while (_NSGetExecutablePath(path, &buflen) != 0)
557 path = (char *) realloc((void *) path, buflen);
558 while (buflen > 0 && path[buflen-1] != '/')
559 buflen--;
560 return std::string(path, buflen);
561 }
562 #elif defined(_WIN32)
563 std::string proc_self_dirname()
564 {
565 int i = 0;
566 # ifdef __MINGW32__
567 char longpath[MAX_PATH + 1];
568 char shortpath[MAX_PATH + 1];
569 # else
570 WCHAR longpath[MAX_PATH + 1];
571 TCHAR shortpath[MAX_PATH + 1];
572 # endif
573 if (!GetModuleFileName(0, longpath, MAX_PATH+1))
574 log_error("GetModuleFileName() failed.\n");
575 if (!GetShortPathName(longpath, shortpath, MAX_PATH+1))
576 log_error("GetShortPathName() failed.\n");
577 while (shortpath[i] != 0)
578 i++;
579 while (i > 0 && shortpath[i-1] != '/' && shortpath[i-1] != '\\')
580 shortpath[--i] = 0;
581 std::string path;
582 for (i = 0; shortpath[i]; i++)
583 path += char(shortpath[i]);
584 return path;
585 }
586 #elif defined(EMSCRIPTEN)
587 std::string proc_self_dirname()
588 {
589 return "/";
590 }
591 #else
592 #error Dont know how to determine process executable base path!
593 #endif
594
595 std::string proc_share_dirname()
596 {
597 std::string proc_self_path = proc_self_dirname();
598 #ifdef _WIN32
599 std::string proc_share_path = proc_self_path + "share\\";
600 if (check_file_exists(proc_share_path, true))
601 return proc_share_path;
602 proc_share_path = proc_self_path + "..\\share\\";
603 if (check_file_exists(proc_share_path, true))
604 return proc_share_path;
605 #else
606 std::string proc_share_path = proc_self_path + "share/";
607 if (check_file_exists(proc_share_path, true))
608 return proc_share_path;
609 proc_share_path = proc_self_path + "../share/yosys/";
610 if (check_file_exists(proc_share_path, true))
611 return proc_share_path;
612 #endif
613 log_error("proc_share_dirname: unable to determine share/ directory!\n");
614 }
615
616 bool fgetline(FILE *f, std::string &buffer)
617 {
618 buffer = "";
619 char block[4096];
620 while (1) {
621 if (fgets(block, 4096, f) == NULL)
622 return false;
623 buffer += block;
624 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
625 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
626 buffer.resize(buffer.size()-1);
627 return true;
628 }
629 }
630 }
631
632 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
633 {
634 int pos = 0;
635 std::string label;
636
637 while (pos < GetSize(command) && (command[pos] == ' ' || command[pos] == '\t'))
638 pos++;
639
640 while (pos < GetSize(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
641 label += command[pos++];
642
643 if (label.back() == ':' && GetSize(label) > 1)
644 {
645 label = label.substr(0, GetSize(label)-1);
646 command = command.substr(pos);
647
648 if (label == run_from)
649 from_to_active = true;
650 else if (label == run_to || (run_from == run_to && !run_from.empty()))
651 from_to_active = false;
652 }
653 }
654
655 void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command, std::string *from_to_label)
656 {
657 if (command == "auto") {
658 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
659 command = "verilog";
660 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
661 command = "verilog -sv";
662 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
663 command = "ilang";
664 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
665 command = "script";
666 else if (filename == "-")
667 command = "script";
668 else
669 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
670 }
671
672 if (command == "script")
673 {
674 std::string run_from, run_to;
675 bool from_to_active = true;
676
677 if (from_to_label != NULL) {
678 size_t pos = from_to_label->find(':');
679 if (pos == std::string::npos) {
680 run_from = *from_to_label;
681 run_to = *from_to_label;
682 } else {
683 run_from = from_to_label->substr(0, pos);
684 run_to = from_to_label->substr(pos+1);
685 }
686 from_to_active = run_from.empty();
687 }
688
689 log("\n-- Executing script file `%s' --\n", filename.c_str());
690
691 FILE *f = stdin;
692
693 if (filename != "-")
694 f = fopen(filename.c_str(), "r");
695
696 if (f == NULL)
697 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
698
699 FILE *backup_script_file = Frontend::current_script_file;
700 Frontend::current_script_file = f;
701
702 try {
703 std::string command;
704 while (fgetline(f, command)) {
705 while (!command.empty() && command[command.size()-1] == '\\') {
706 std::string next_line;
707 if (!fgetline(f, next_line))
708 break;
709 command.resize(command.size()-1);
710 command += next_line;
711 }
712 handle_label(command, from_to_active, run_from, run_to);
713 if (from_to_active)
714 Pass::call(design, command);
715 }
716
717 if (!command.empty()) {
718 handle_label(command, from_to_active, run_from, run_to);
719 if (from_to_active)
720 Pass::call(design, command);
721 }
722 }
723 catch (...) {
724 Frontend::current_script_file = backup_script_file;
725 throw;
726 }
727
728 Frontend::current_script_file = backup_script_file;
729
730 if (filename != "-")
731 fclose(f);
732
733 if (backend_command != NULL && *backend_command == "auto")
734 *backend_command = "";
735
736 return;
737 }
738
739 if (filename == "-") {
740 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
741 } else {
742 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
743 }
744
745 Frontend::frontend_call(design, NULL, filename, command);
746 }
747
748 void run_pass(std::string command, RTLIL::Design *design)
749 {
750 log("\n-- Running pass `%s' --\n", command.c_str());
751
752 Pass::call(design, command);
753 }
754
755 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
756 {
757 if (command == "auto") {
758 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
759 command = "verilog";
760 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
761 command = "ilang";
762 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
763 command = "blif";
764 else if (filename == "-")
765 command = "ilang";
766 else if (filename.empty())
767 return;
768 else
769 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
770 }
771
772 if (filename.empty())
773 filename = "-";
774
775 if (filename == "-") {
776 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
777 } else {
778 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
779 }
780
781 Backend::backend_call(design, NULL, filename, command);
782 }
783
784 #ifdef YOSYS_ENABLE_READLINE
785 static char *readline_cmd_generator(const char *text, int state)
786 {
787 static std::map<std::string, Pass*>::iterator it;
788 static int len;
789
790 if (!state) {
791 it = pass_register.begin();
792 len = strlen(text);
793 }
794
795 for (; it != pass_register.end(); it++) {
796 if (it->first.substr(0, len) == text)
797 return strdup((it++)->first.c_str());
798 }
799 return NULL;
800 }
801
802 static char *readline_obj_generator(const char *text, int state)
803 {
804 static std::vector<char*> obj_names;
805 static size_t idx;
806
807 if (!state)
808 {
809 idx = 0;
810 obj_names.clear();
811
812 RTLIL::Design *design = yosys_get_design();
813 int len = strlen(text);
814
815 if (design->selected_active_module.empty())
816 {
817 for (auto &it : design->modules_)
818 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
819 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
820 }
821 else
822 if (design->modules_.count(design->selected_active_module) > 0)
823 {
824 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
825
826 for (auto &it : module->wires_)
827 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
828 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
829
830 for (auto &it : module->memories)
831 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
832 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
833
834 for (auto &it : module->cells_)
835 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
836 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
837
838 for (auto &it : module->processes)
839 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
840 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
841 }
842
843 std::sort(obj_names.begin(), obj_names.end());
844 }
845
846 if (idx < obj_names.size())
847 return strdup(obj_names[idx++]);
848
849 idx = 0;
850 obj_names.clear();
851 return NULL;
852 }
853
854 static char **readline_completion(const char *text, int start, int)
855 {
856 if (start == 0)
857 return rl_completion_matches(text, readline_cmd_generator);
858 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
859 return rl_completion_matches(text, readline_obj_generator);
860 return NULL;
861 }
862 #endif
863
864 void shell(RTLIL::Design *design)
865 {
866 static int recursion_counter = 0;
867
868 recursion_counter++;
869 log_cmd_error_throw = true;
870
871 #ifdef YOSYS_ENABLE_READLINE
872 rl_readline_name = "yosys";
873 rl_attempted_completion_function = readline_completion;
874 rl_basic_word_break_characters = " \t\n";
875 #endif
876
877 char *command = NULL;
878 #ifdef YOSYS_ENABLE_READLINE
879 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
880 {
881 #else
882 char command_buffer[4096];
883 while (1)
884 {
885 fputs(create_prompt(design, recursion_counter), stdout);
886 fflush(stdout);
887 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
888 break;
889 #endif
890 if (command[strspn(command, " \t\r\n")] == 0)
891 continue;
892 #ifdef YOSYS_ENABLE_READLINE
893 add_history(command);
894 #endif
895
896 char *p = command + strspn(command, " \t\r\n");
897 if (!strncmp(p, "exit", 4)) {
898 p += 4;
899 p += strspn(p, " \t\r\n");
900 if (*p == 0)
901 break;
902 }
903
904 try {
905 log_assert(design->selection_stack.size() == 1);
906 Pass::call(design, command);
907 } catch (log_cmd_error_exception) {
908 while (design->selection_stack.size() > 1)
909 design->selection_stack.pop_back();
910 log_reset_stack();
911 }
912 }
913 if (command == NULL)
914 printf("exit\n");
915
916 recursion_counter--;
917 log_cmd_error_throw = false;
918 }
919
920 struct ShellPass : public Pass {
921 ShellPass() : Pass("shell", "enter interactive command mode") { }
922 virtual void help() {
923 log("\n");
924 log(" shell\n");
925 log("\n");
926 log("This command enters the interactive command mode. This can be useful\n");
927 log("in a script to interrupt the script at a certain point and allow for\n");
928 log("interactive inspection or manual synthesis of the design at this point.\n");
929 log("\n");
930 log("The command prompt of the interactive shell indicates the current\n");
931 log("selection (see 'help select'):\n");
932 log("\n");
933 log(" yosys>\n");
934 log(" the entire design is selected\n");
935 log("\n");
936 log(" yosys*>\n");
937 log(" only part of the design is selected\n");
938 log("\n");
939 log(" yosys [modname]>\n");
940 log(" the entire module 'modname' is selected using 'select -module modname'\n");
941 log("\n");
942 log(" yosys [modname]*>\n");
943 log(" only part of current module 'modname' is selected\n");
944 log("\n");
945 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
946 log("do not terminate yosys but return to the command prompt.\n");
947 log("\n");
948 log("This command is the default action if nothing else has been specified\n");
949 log("on the command line.\n");
950 log("\n");
951 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
952 log("\n");
953 }
954 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
955 extra_args(args, 1, design, false);
956 shell(design);
957 }
958 } ShellPass;
959
960 #ifdef YOSYS_ENABLE_READLINE
961 struct HistoryPass : public Pass {
962 HistoryPass() : Pass("history", "show last interactive commands") { }
963 virtual void help() {
964 log("\n");
965 log(" history\n");
966 log("\n");
967 log("This command prints all commands in the shell history buffer. This are\n");
968 log("all commands executed in an interactive session, but not the commands\n");
969 log("from executed scripts.\n");
970 log("\n");
971 }
972 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
973 extra_args(args, 1, design, false);
974 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
975 log("%s\n", (*list)->line);
976 }
977 } HistoryPass;
978 #endif
979
980 struct ScriptPass : public Pass {
981 ScriptPass() : Pass("script", "execute commands from script file") { }
982 virtual void help() {
983 log("\n");
984 log(" script <filename> [<from_label>:<to_label>]\n");
985 log("\n");
986 log("This command executes the yosys commands in the specified file.\n");
987 log("\n");
988 log("The 2nd argument can be used to only execute the section of the\n");
989 log("file between the specified labels. An empty from label is synonymous\n");
990 log("for the beginning of the file and an empty to label is synonymous\n");
991 log("for the end of the file.\n");
992 log("\n");
993 log("If only one label is specified (without ':') then only the block\n");
994 log("marked with that label (until the next label) is executed.\n");
995 log("\n");
996 }
997 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
998 if (args.size() < 2)
999 log_cmd_error("Missing script file.\n");
1000 else if (args.size() == 2)
1001 run_frontend(args[1], "script", design, NULL, NULL);
1002 else if (args.size() == 3)
1003 run_frontend(args[1], "script", design, NULL, &args[2]);
1004 else
1005 extra_args(args, 2, design, false);
1006 }
1007 } ScriptPass;
1008
1009 YOSYS_NAMESPACE_END
1010