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