ac1bc7abfaa5b5767cc3fa7a869f913532ef84e3
[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 size_t pos = template_str.rfind("XXXXXX");
323 log_assert(pos != std::string::npos);
324
325 int suffixlen = GetSize(template_str) - pos - 6;
326 log_assert(suffixlen == 0);
327
328 char *p = strdup(template_str.c_str());
329 p = mkdtemp(p);
330 log_assert(p != NULL);
331 template_str = p;
332 free(p);
333
334 return template_str;
335 #endif
336 }
337
338 #ifdef _WIN32
339 bool check_file_exists(std::string filename, bool)
340 {
341 return _access(filename.c_str(), 0) == 0;
342 }
343 #else
344 bool check_file_exists(std::string filename, bool is_exec)
345 {
346 return access(filename.c_str(), is_exec ? X_OK : F_OK) == 0;
347 }
348 #endif
349
350 void remove_directory(std::string dirname)
351 {
352 #ifdef _WIN32
353 run_command(stringf("rmdir /s /q \"%s\"", dirname.c_str()));
354 #else
355 struct stat stbuf;
356 struct dirent **namelist;
357 int n = scandir(dirname.c_str(), &namelist, nullptr, alphasort);
358 log_assert(n >= 0);
359 for (int i = 0; i < n; i++) {
360 if (strcmp(namelist[i]->d_name, ".") && strcmp(namelist[i]->d_name, "..")) {
361 std::string buffer = stringf("%s/%s", dirname.c_str(), namelist[i]->d_name);
362 if (!stat(buffer.c_str(), &stbuf) && S_ISREG(stbuf.st_mode)) {
363 remove(buffer.c_str());
364 } else
365 remove_directory(buffer);
366 }
367 free(namelist[i]);
368 }
369 free(namelist);
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 // if there are already IdString objects then we have a global initialization order bug
382 IdString empty_id;
383 log_assert(empty_id.index_ == 0);
384 IdString::get_reference(empty_id.index_);
385
386 Pass::init_register();
387 yosys_design = new RTLIL::Design;
388 yosys_celltypes.setup();
389 log_push();
390 }
391
392 void yosys_shutdown()
393 {
394 log_pop();
395
396 delete yosys_design;
397 yosys_design = NULL;
398
399 for (auto f : log_files)
400 if (f != stderr)
401 fclose(f);
402 log_errfile = NULL;
403 log_files.clear();
404
405 Pass::done_register();
406 yosys_celltypes.clear();
407
408 #ifdef YOSYS_ENABLE_TCL
409 if (yosys_tcl_interp != NULL) {
410 Tcl_DeleteInterp(yosys_tcl_interp);
411 Tcl_Finalize();
412 yosys_tcl_interp = NULL;
413 }
414 #endif
415
416 #ifdef YOSYS_ENABLE_PLUGINS
417 for (auto &it : loaded_plugins)
418 dlclose(it.second);
419
420 loaded_plugins.clear();
421 loaded_plugin_aliases.clear();
422 #endif
423
424 IdString empty_id;
425 IdString::put_reference(empty_id.index_);
426 }
427
428 RTLIL::IdString new_id(std::string file, int line, std::string func)
429 {
430 #ifdef _WIN32
431 size_t pos = file.find_last_of("/\\");
432 #else
433 size_t pos = file.find_last_of('/');
434 #endif
435 if (pos != std::string::npos)
436 file = file.substr(pos+1);
437
438 pos = func.find_last_of(':');
439 if (pos != std::string::npos)
440 func = func.substr(pos+1);
441
442 return stringf("$auto$%s:%d:%s$%d", file.c_str(), line, func.c_str(), autoidx++);
443 }
444
445 RTLIL::Design *yosys_get_design()
446 {
447 return yosys_design;
448 }
449
450 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
451 {
452 static char buffer[100];
453 std::string str = "\n";
454 if (recursion_counter > 1)
455 str += stringf("(%d) ", recursion_counter);
456 str += "yosys";
457 if (!design->selected_active_module.empty())
458 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
459 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
460 if (design->selected_active_module.empty())
461 str += "*";
462 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
463 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
464 str += "*";
465 }
466 snprintf(buffer, 100, "%s> ", str.c_str());
467 return buffer;
468 }
469
470 #ifdef YOSYS_ENABLE_TCL
471 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
472 {
473 std::vector<std::string> args;
474 for (int i = 1; i < argc; i++)
475 args.push_back(argv[i]);
476
477 if (args.size() >= 1 && args[0] == "-import") {
478 for (auto &it : pass_register) {
479 std::string tcl_command_name = it.first;
480 if (tcl_command_name == "proc")
481 tcl_command_name = "procs";
482 Tcl_CmdInfo info;
483 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
484 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
485 } else {
486 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
487 Tcl_Eval(interp, tcl_script.c_str());
488 }
489 }
490 return TCL_OK;
491 }
492
493 if (args.size() == 1) {
494 Pass::call(yosys_get_design(), args[0]);
495 return TCL_OK;
496 }
497
498 Pass::call(yosys_get_design(), args);
499 return TCL_OK;
500 }
501
502 extern Tcl_Interp *yosys_get_tcl_interp()
503 {
504 if (yosys_tcl_interp == NULL) {
505 yosys_tcl_interp = Tcl_CreateInterp();
506 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
507 }
508 return yosys_tcl_interp;
509 }
510
511 struct TclPass : public Pass {
512 TclPass() : Pass("tcl", "execute a TCL script file") { }
513 virtual void help() {
514 log("\n");
515 log(" tcl <filename>\n");
516 log("\n");
517 log("This command executes the tcl commands in the specified file.\n");
518 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
519 log("\n");
520 log("The tcl command 'yosys -import' can be used to import all yosys\n");
521 log("commands directly as tcl commands to the tcl shell. The yosys\n");
522 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
523 log("to avoid a name collision with the tcl builting command 'proc'.\n");
524 log("\n");
525 }
526 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
527 if (args.size() < 2)
528 log_cmd_error("Missing script file.\n");
529 if (args.size() > 2)
530 extra_args(args, 1, design, false);
531 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
532 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
533 }
534 } TclPass;
535 #endif
536
537 #if defined(__linux__)
538 std::string proc_self_dirname()
539 {
540 char path[PATH_MAX];
541 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
542 if (buflen < 0) {
543 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
544 }
545 while (buflen > 0 && path[buflen-1] != '/')
546 buflen--;
547 return std::string(path, buflen);
548 }
549 #elif defined(__APPLE__)
550 std::string proc_self_dirname()
551 {
552 char *path = NULL;
553 uint32_t buflen = 0;
554 while (_NSGetExecutablePath(path, &buflen) != 0)
555 path = (char *) realloc((void *) path, buflen);
556 while (buflen > 0 && path[buflen-1] != '/')
557 buflen--;
558 return std::string(path, buflen);
559 }
560 #elif defined(_WIN32)
561 std::string proc_self_dirname()
562 {
563 int i = 0;
564 # ifdef __MINGW32__
565 char longpath[MAX_PATH + 1];
566 char shortpath[MAX_PATH + 1];
567 # else
568 WCHAR longpath[MAX_PATH + 1];
569 TCHAR shortpath[MAX_PATH + 1];
570 # endif
571 if (!GetModuleFileName(0, longpath, MAX_PATH+1))
572 log_error("GetModuleFileName() failed.\n");
573 if (!GetShortPathName(longpath, shortpath, MAX_PATH+1))
574 log_error("GetShortPathName() failed.\n");
575 while (shortpath[i] != 0)
576 i++;
577 while (i > 0 && shortpath[i-1] != '/' && shortpath[i-1] != '\\')
578 shortpath[--i] = 0;
579 std::string path;
580 for (i = 0; shortpath[i]; i++)
581 path += char(shortpath[i]);
582 return path;
583 }
584 #elif defined(EMSCRIPTEN)
585 std::string proc_self_dirname()
586 {
587 return "/";
588 }
589 #else
590 #error Dont know how to determine process executable base path!
591 #endif
592
593 std::string proc_share_dirname()
594 {
595 std::string proc_self_path = proc_self_dirname();
596 #ifdef _WIN32
597 std::string proc_share_path = proc_self_path + "share\\";
598 if (check_file_exists(proc_share_path, true))
599 return proc_share_path;
600 proc_share_path = proc_self_path + "..\\share\\";
601 if (check_file_exists(proc_share_path, true))
602 return proc_share_path;
603 #else
604 std::string proc_share_path = proc_self_path + "share/";
605 if (check_file_exists(proc_share_path, true))
606 return proc_share_path;
607 proc_share_path = proc_self_path + "../share/yosys/";
608 if (check_file_exists(proc_share_path, true))
609 return proc_share_path;
610 #endif
611 log_error("proc_share_dirname: unable to determine share/ directory!\n");
612 }
613
614 bool fgetline(FILE *f, std::string &buffer)
615 {
616 buffer = "";
617 char block[4096];
618 while (1) {
619 if (fgets(block, 4096, f) == NULL)
620 return false;
621 buffer += block;
622 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
623 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
624 buffer.resize(buffer.size()-1);
625 return true;
626 }
627 }
628 }
629
630 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
631 {
632 int pos = 0;
633 std::string label;
634
635 while (pos < GetSize(command) && (command[pos] == ' ' || command[pos] == '\t'))
636 pos++;
637
638 while (pos < GetSize(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
639 label += command[pos++];
640
641 if (label.back() == ':' && GetSize(label) > 1)
642 {
643 label = label.substr(0, GetSize(label)-1);
644 command = command.substr(pos);
645
646 if (label == run_from)
647 from_to_active = true;
648 else if (label == run_to || (run_from == run_to && !run_from.empty()))
649 from_to_active = false;
650 }
651 }
652
653 void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command, std::string *from_to_label)
654 {
655 if (command == "auto") {
656 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
657 command = "verilog";
658 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
659 command = "verilog -sv";
660 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
661 command = "ilang";
662 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
663 command = "script";
664 else if (filename == "-")
665 command = "script";
666 else
667 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
668 }
669
670 if (command == "script")
671 {
672 std::string run_from, run_to;
673 bool from_to_active = true;
674
675 if (from_to_label != NULL) {
676 size_t pos = from_to_label->find(':');
677 if (pos == std::string::npos) {
678 run_from = *from_to_label;
679 run_to = *from_to_label;
680 } else {
681 run_from = from_to_label->substr(0, pos);
682 run_to = from_to_label->substr(pos+1);
683 }
684 from_to_active = run_from.empty();
685 }
686
687 log("\n-- Executing script file `%s' --\n", filename.c_str());
688
689 FILE *f = stdin;
690
691 if (filename != "-")
692 f = fopen(filename.c_str(), "r");
693
694 if (f == NULL)
695 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
696
697 FILE *backup_script_file = Frontend::current_script_file;
698 Frontend::current_script_file = f;
699
700 try {
701 std::string command;
702 while (fgetline(f, command)) {
703 while (!command.empty() && command[command.size()-1] == '\\') {
704 std::string next_line;
705 if (!fgetline(f, next_line))
706 break;
707 command.resize(command.size()-1);
708 command += next_line;
709 }
710 handle_label(command, from_to_active, run_from, run_to);
711 if (from_to_active)
712 Pass::call(design, command);
713 }
714
715 if (!command.empty()) {
716 handle_label(command, from_to_active, run_from, run_to);
717 if (from_to_active)
718 Pass::call(design, command);
719 }
720 }
721 catch (log_cmd_error_exception) {
722 Frontend::current_script_file = backup_script_file;
723 throw log_cmd_error_exception();
724 }
725
726 Frontend::current_script_file = backup_script_file;
727
728 if (filename != "-")
729 fclose(f);
730
731 if (backend_command != NULL && *backend_command == "auto")
732 *backend_command = "";
733
734 return;
735 }
736
737 if (filename == "-") {
738 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
739 } else {
740 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
741 }
742
743 Frontend::frontend_call(design, NULL, filename, command);
744 }
745
746 void run_pass(std::string command, RTLIL::Design *design)
747 {
748 log("\n-- Running pass `%s' --\n", command.c_str());
749
750 Pass::call(design, command);
751 }
752
753 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
754 {
755 if (command == "auto") {
756 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
757 command = "verilog";
758 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
759 command = "ilang";
760 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
761 command = "blif";
762 else if (filename == "-")
763 command = "ilang";
764 else if (filename.empty())
765 return;
766 else
767 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
768 }
769
770 if (filename.empty())
771 filename = "-";
772
773 if (filename == "-") {
774 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
775 } else {
776 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
777 }
778
779 Backend::backend_call(design, NULL, filename, command);
780 }
781
782 #ifdef YOSYS_ENABLE_READLINE
783 static char *readline_cmd_generator(const char *text, int state)
784 {
785 static std::map<std::string, Pass*>::iterator it;
786 static int len;
787
788 if (!state) {
789 it = pass_register.begin();
790 len = strlen(text);
791 }
792
793 for (; it != pass_register.end(); it++) {
794 if (it->first.substr(0, len) == text)
795 return strdup((it++)->first.c_str());
796 }
797 return NULL;
798 }
799
800 static char *readline_obj_generator(const char *text, int state)
801 {
802 static std::vector<char*> obj_names;
803 static size_t idx;
804
805 if (!state)
806 {
807 idx = 0;
808 obj_names.clear();
809
810 RTLIL::Design *design = yosys_get_design();
811 int len = strlen(text);
812
813 if (design->selected_active_module.empty())
814 {
815 for (auto &it : design->modules_)
816 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
817 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
818 }
819 else
820 if (design->modules_.count(design->selected_active_module) > 0)
821 {
822 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
823
824 for (auto &it : module->wires_)
825 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
826 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
827
828 for (auto &it : module->memories)
829 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
830 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
831
832 for (auto &it : module->cells_)
833 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
834 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
835
836 for (auto &it : module->processes)
837 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
838 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
839 }
840
841 std::sort(obj_names.begin(), obj_names.end());
842 }
843
844 if (idx < obj_names.size())
845 return strdup(obj_names[idx++]);
846
847 idx = 0;
848 obj_names.clear();
849 return NULL;
850 }
851
852 static char **readline_completion(const char *text, int start, int)
853 {
854 if (start == 0)
855 return rl_completion_matches(text, readline_cmd_generator);
856 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
857 return rl_completion_matches(text, readline_obj_generator);
858 return NULL;
859 }
860 #endif
861
862 void shell(RTLIL::Design *design)
863 {
864 static int recursion_counter = 0;
865
866 recursion_counter++;
867 log_cmd_error_throw = true;
868
869 #ifdef YOSYS_ENABLE_READLINE
870 rl_readline_name = "yosys";
871 rl_attempted_completion_function = readline_completion;
872 rl_basic_word_break_characters = " \t\n";
873 #endif
874
875 char *command = NULL;
876 #ifdef YOSYS_ENABLE_READLINE
877 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
878 {
879 #else
880 char command_buffer[4096];
881 while (1)
882 {
883 fputs(create_prompt(design, recursion_counter), stdout);
884 fflush(stdout);
885 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
886 break;
887 #endif
888 if (command[strspn(command, " \t\r\n")] == 0)
889 continue;
890 #ifdef YOSYS_ENABLE_READLINE
891 add_history(command);
892 #endif
893
894 char *p = command + strspn(command, " \t\r\n");
895 if (!strncmp(p, "exit", 4)) {
896 p += 4;
897 p += strspn(p, " \t\r\n");
898 if (*p == 0)
899 break;
900 }
901
902 try {
903 log_assert(design->selection_stack.size() == 1);
904 Pass::call(design, command);
905 } catch (log_cmd_error_exception) {
906 while (design->selection_stack.size() > 1)
907 design->selection_stack.pop_back();
908 log_reset_stack();
909 }
910 }
911 if (command == NULL)
912 printf("exit\n");
913
914 recursion_counter--;
915 log_cmd_error_throw = false;
916 }
917
918 struct ShellPass : public Pass {
919 ShellPass() : Pass("shell", "enter interactive command mode") { }
920 virtual void help() {
921 log("\n");
922 log(" shell\n");
923 log("\n");
924 log("This command enters the interactive command mode. This can be useful\n");
925 log("in a script to interrupt the script at a certain point and allow for\n");
926 log("interactive inspection or manual synthesis of the design at this point.\n");
927 log("\n");
928 log("The command prompt of the interactive shell indicates the current\n");
929 log("selection (see 'help select'):\n");
930 log("\n");
931 log(" yosys>\n");
932 log(" the entire design is selected\n");
933 log("\n");
934 log(" yosys*>\n");
935 log(" only part of the design is selected\n");
936 log("\n");
937 log(" yosys [modname]>\n");
938 log(" the entire module 'modname' is selected using 'select -module modname'\n");
939 log("\n");
940 log(" yosys [modname]*>\n");
941 log(" only part of current module 'modname' is selected\n");
942 log("\n");
943 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
944 log("do not terminate yosys but return to the command prompt.\n");
945 log("\n");
946 log("This command is the default action if nothing else has been specified\n");
947 log("on the command line.\n");
948 log("\n");
949 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
950 log("\n");
951 }
952 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
953 extra_args(args, 1, design, false);
954 shell(design);
955 }
956 } ShellPass;
957
958 #ifdef YOSYS_ENABLE_READLINE
959 struct HistoryPass : public Pass {
960 HistoryPass() : Pass("history", "show last interactive commands") { }
961 virtual void help() {
962 log("\n");
963 log(" history\n");
964 log("\n");
965 log("This command prints all commands in the shell history buffer. This are\n");
966 log("all commands executed in an interactive session, but not the commands\n");
967 log("from executed scripts.\n");
968 log("\n");
969 }
970 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
971 extra_args(args, 1, design, false);
972 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
973 log("%s\n", (*list)->line);
974 }
975 } HistoryPass;
976 #endif
977
978 struct ScriptPass : public Pass {
979 ScriptPass() : Pass("script", "execute commands from script file") { }
980 virtual void help() {
981 log("\n");
982 log(" script <filename> [<from_label>:<to_label>]\n");
983 log("\n");
984 log("This command executes the yosys commands in the specified file.\n");
985 log("\n");
986 log("The 2nd argument can be used to only execute the section of the\n");
987 log("file between the specified labels. An empty from label is synonymous\n");
988 log("for the beginning of the file and an empty to label is synonymous\n");
989 log("for the end of the file.\n");
990 log("\n");
991 log("If only one label is specified (without ':') then only the block\n");
992 log("marked with that label (until the next label) is executed.\n");
993 log("\n");
994 }
995 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
996 if (args.size() < 2)
997 log_cmd_error("Missing script file.\n");
998 else if (args.size() == 2)
999 run_frontend(args[1], "script", design, NULL, NULL);
1000 else if (args.size() == 3)
1001 run_frontend(args[1], "script", design, NULL, &args[2]);
1002 else
1003 extra_args(args, 2, design, false);
1004 }
1005 } ScriptPass;
1006
1007 YOSYS_NAMESPACE_END
1008