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