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