2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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.
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.
20 #include "kernel/yosys.h"
21 #include "kernel/celltypes.h"
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
28 #ifdef YOSYS_ENABLE_EDITLINE
29 # include <editline/readline.h>
32 #ifdef YOSYS_ENABLE_PLUGINS
39 #elif defined(__APPLE__)
40 # include <mach-o/dyld.h>
43 # include <sys/stat.h>
48 # include <sys/types.h>
49 # include <sys/wait.h>
50 # include <sys/stat.h>
55 # include <sys/sysctl.h>
59 #if PY_MAJOR_VERSION >= 3
60 # define INIT_MODULE PyInit_libyosys
61 extern "C" PyObject
* INIT_MODULE();
63 # define INIT_MODULE initlibyosys
64 extern "C" void INIT_MODULE();
75 RTLIL::Design
*yosys_design
= NULL
;
76 CellTypes yosys_celltypes
;
78 #ifdef YOSYS_ENABLE_TCL
79 Tcl_Interp
*yosys_tcl_interp
= NULL
;
82 std::set
<std::string
> yosys_input_files
, yosys_output_files
;
84 bool memhasher_active
= false;
85 uint32_t memhasher_rng
= 123456;
86 std::vector
<void*> memhasher_store
;
90 #if defined(__linux__) || defined(__FreeBSD__)
91 memhasher_rng
+= time(NULL
) << 16 ^ getpid();
93 memhasher_store
.resize(0x10000);
94 memhasher_active
= true;
99 for (auto p
: memhasher_store
)
101 memhasher_store
.clear();
102 memhasher_active
= false;
107 memhasher_rng
^= memhasher_rng
<< 13;
108 memhasher_rng
^= memhasher_rng
>> 17;
109 memhasher_rng
^= memhasher_rng
<< 5;
111 int size
, index
= (memhasher_rng
>> 4) & 0xffff;
112 switch (memhasher_rng
& 7) {
113 case 0: size
= 16; break;
114 case 1: size
= 256; break;
115 case 2: size
= 1024; break;
116 case 3: size
= 4096; break;
119 if (index
< 16) size
*= 16;
120 memhasher_store
[index
] = realloc(memhasher_store
[index
], size
);
126 log(" /----------------------------------------------------------------------------\\\n");
128 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
130 log(" | Copyright (C) 2012 - 2018 Clifford Wolf <clifford@clifford.at> |\n");
132 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
133 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
134 log(" | copyright notice and this permission notice appear in all copies. |\n");
136 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
137 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
138 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
139 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
140 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
141 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
142 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
144 log(" \\----------------------------------------------------------------------------/\n");
146 log(" %s\n", yosys_version_str
);
155 for (int i
= 0; i
< 32; i
++)
156 if (((x
-1) >> i
) == 0)
162 std::string
stringf(const char *fmt
, ...)
168 string
= vstringf(fmt
, ap
);
174 std::string
vstringf(const char *fmt
, va_list ap
)
184 str
= (char*)realloc(str
, sz
);
185 rc
= vsnprintf(str
, sz
, fmt
, apc
);
187 if (rc
>= 0 && rc
< sz
)
192 if (vasprintf(&str
, fmt
, ap
) < 0)
204 int readsome(std::istream
&f
, char *s
, int n
)
206 int rc
= int(f
.readsome(s
, n
));
208 // f.readsome() sometimes returns 0 on a non-empty stream..
220 std::string
next_token(std::string
&text
, const char *sep
, bool long_strings
)
222 size_t pos_begin
= text
.find_first_not_of(sep
);
224 if (pos_begin
== std::string::npos
)
225 pos_begin
= text
.size();
227 if (long_strings
&& pos_begin
!= text
.size() && text
[pos_begin
] == '"') {
228 string sep_string
= sep
;
229 for (size_t i
= pos_begin
+1; i
< text
.size(); i
++)
230 if (text
[i
] == '"' && (i
+1 == text
.size() || sep_string
.find(text
[i
+1]) != std::string::npos
)) {
231 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
232 text
= text
.substr(i
+1);
237 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
239 if (pos_end
== std::string::npos
)
240 pos_end
= text
.size();
242 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
243 text
= text
.substr(pos_end
);
247 std::vector
<std::string
> split_tokens(const std::string
&text
, const char *sep
)
249 std::vector
<std::string
> tokens
;
250 std::string current_token
;
251 for (char c
: text
) {
252 if (strchr(sep
, c
)) {
253 if (!current_token
.empty()) {
254 tokens
.push_back(current_token
);
255 current_token
.clear();
260 if (!current_token
.empty()) {
261 tokens
.push_back(current_token
);
262 current_token
.clear();
267 // this is very similar to fnmatch(). the exact rules used by this
270 // ? matches any character except
271 // * matches any sequence of characters
272 // [...] matches any of the characters in the list
273 // [!..] matches any of the characters not in the list
275 // a backslash may be used to escape the next characters in the
276 // pattern. each special character can also simply match itself.
278 bool patmatch(const char *pattern
, const char *string
)
283 if (*pattern
== '\\') {
284 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
288 if (*pattern
== '?') {
291 return patmatch(pattern
+1, string
+1);
294 if (*pattern
== '*') {
296 if (patmatch(pattern
+1, string
++))
299 return pattern
[1] == 0;
302 if (*pattern
== '[') {
303 bool found_match
= false;
304 bool inverted_list
= pattern
[1] == '!';
305 const char *p
= pattern
+ (inverted_list
? 1 : 0);
309 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
323 if (*pattern
== *string
)
324 return patmatch(pattern
+1, string
+1);
329 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
332 return system(command
.c_str());
334 FILE *f
= popen(command
.c_str(), "r");
340 while (fgets(logbuf
, 128, f
) != NULL
) {
342 if (!line
.empty() && line
.back() == '\n')
343 process_line(line
), line
.clear();
354 return WEXITSTATUS(ret
);
358 std::string
make_temp_file(std::string template_str
)
361 if (template_str
.rfind("/tmp/", 0) == 0) {
363 char longpath
[MAX_PATH
+ 1];
364 char shortpath
[MAX_PATH
+ 1];
366 WCHAR longpath
[MAX_PATH
+ 1];
367 TCHAR shortpath
[MAX_PATH
+ 1];
369 if (!GetTempPath(MAX_PATH
+1, longpath
))
370 log_error("GetTempPath() failed.\n");
371 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+ 1))
372 log_error("GetShortPathName() failed.\n");
374 for (int i
= 0; shortpath
[i
]; i
++)
375 path
+= char(shortpath
[i
]);
376 template_str
= stringf("%s\\%s", path
.c_str(), template_str
.c_str() + 5);
379 size_t pos
= template_str
.rfind("XXXXXX");
380 log_assert(pos
!= std::string::npos
);
383 for (int i
= 0; i
< 6; i
++) {
384 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
385 static uint32_t x
= 314159265 ^ uint32_t(time(NULL
));
386 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
387 template_str
[pos
+i
] = y
[x
% y
.size()];
389 if (_access(template_str
.c_str(), 0) != 0)
393 size_t pos
= template_str
.rfind("XXXXXX");
394 log_assert(pos
!= std::string::npos
);
396 int suffixlen
= GetSize(template_str
) - pos
- 6;
398 char *p
= strdup(template_str
.c_str());
399 close(mkstemps(p
, suffixlen
));
407 std::string
make_temp_dir(std::string template_str
)
410 template_str
= make_temp_file(template_str
);
411 mkdir(template_str
.c_str());
415 size_t pos
= template_str
.rfind("XXXXXX");
416 log_assert(pos
!= std::string::npos
);
418 int suffixlen
= GetSize(template_str
) - pos
- 6;
419 log_assert(suffixlen
== 0);
422 char *p
= strdup(template_str
.c_str());
424 log_assert(p
!= NULL
);
433 bool check_file_exists(std::string filename
, bool)
435 return _access(filename
.c_str(), 0) == 0;
438 bool check_file_exists(std::string filename
, bool is_exec
)
440 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
444 bool is_absolute_path(std::string filename
)
447 return filename
[0] == '/' || filename
[0] == '\\' || (filename
[0] != 0 && filename
[1] == ':');
449 return filename
[0] == '/';
453 void remove_directory(std::string dirname
)
456 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
459 struct dirent
**namelist
;
460 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
462 for (int i
= 0; i
< n
; i
++) {
463 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
464 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
465 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
466 remove(buffer
.c_str());
468 remove_directory(buffer
);
473 rmdir(dirname
.c_str());
477 int GetSize(RTLIL::Wire
*wire
)
482 bool already_setup
= false;
488 already_setup
= true;
489 // if there are already IdString objects then we have a global initialization order bug
491 log_assert(empty_id
.index_
== 0);
492 IdString::get_reference(empty_id
.index_
);
495 PyImport_AppendInittab((char*)"libyosys", INIT_MODULE
);
497 PyRun_SimpleString("import sys");
500 Pass::init_register();
501 yosys_design
= new RTLIL::Design
;
502 yosys_celltypes
.setup();
506 bool yosys_already_setup()
508 return already_setup
;
511 bool already_shutdown
= false;
513 void yosys_shutdown()
517 already_shutdown
= true;
523 for (auto f
: log_files
)
529 Pass::done_register();
530 yosys_celltypes
.clear();
532 #ifdef YOSYS_ENABLE_TCL
533 if (yosys_tcl_interp
!= NULL
) {
534 Tcl_DeleteInterp(yosys_tcl_interp
);
536 yosys_tcl_interp
= NULL
;
540 #ifdef YOSYS_ENABLE_PLUGINS
541 for (auto &it
: loaded_plugins
)
544 loaded_plugins
.clear();
546 loaded_python_plugins
.clear();
548 loaded_plugin_aliases
.clear();
556 IdString::put_reference(empty_id
.index_
);
559 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
562 size_t pos
= file
.find_last_of("/\\");
564 size_t pos
= file
.find_last_of('/');
566 if (pos
!= std::string::npos
)
567 file
= file
.substr(pos
+1);
569 pos
= func
.find_last_of(':');
570 if (pos
!= std::string::npos
)
571 func
= func
.substr(pos
+1);
573 return stringf("$auto$%s:%d:%s$%d", file
.c_str(), line
, func
.c_str(), autoidx
++);
576 RTLIL::Design
*yosys_get_design()
581 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
583 static char buffer
[100];
584 std::string str
= "\n";
585 if (recursion_counter
> 1)
586 str
+= stringf("(%d) ", recursion_counter
);
588 if (!design
->selected_active_module
.empty())
589 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
590 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
591 if (design
->selected_active_module
.empty())
593 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
594 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
597 snprintf(buffer
, 100, "%s> ", str
.c_str());
601 std::vector
<std::string
> glob_filename(const std::string
&filename_pattern
)
603 std::vector
<std::string
> results
;
606 results
.push_back(filename_pattern
);
610 int err
= glob(filename_pattern
.c_str(), 0, NULL
, &globbuf
);
613 for (size_t i
= 0; i
< globbuf
.gl_pathc
; i
++)
614 results
.push_back(globbuf
.gl_pathv
[i
]);
617 results
.push_back(filename_pattern
);
624 void rewrite_filename(std::string
&filename
)
626 if (filename
.substr(0, 1) == "\"" && filename
.substr(GetSize(filename
)-1) == "\"")
627 filename
= filename
.substr(1, GetSize(filename
)-2);
628 if (filename
.substr(0, 2) == "+/")
629 filename
= proc_share_dirname() + filename
.substr(2);
632 #ifdef YOSYS_ENABLE_TCL
633 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
635 std::vector
<std::string
> args
;
636 for (int i
= 1; i
< argc
; i
++)
637 args
.push_back(argv
[i
]);
639 if (args
.size() >= 1 && args
[0] == "-import") {
640 for (auto &it
: pass_register
) {
641 std::string tcl_command_name
= it
.first
;
642 if (tcl_command_name
== "proc")
643 tcl_command_name
= "procs";
644 else if (tcl_command_name
== "rename")
645 tcl_command_name
= "renames";
647 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
648 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
650 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
651 Tcl_Eval(interp
, tcl_script
.c_str());
657 if (args
.size() == 1) {
658 Pass::call(yosys_get_design(), args
[0]);
662 Pass::call(yosys_get_design(), args
);
666 extern Tcl_Interp
*yosys_get_tcl_interp()
668 if (yosys_tcl_interp
== NULL
) {
669 yosys_tcl_interp
= Tcl_CreateInterp();
670 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
672 return yosys_tcl_interp
;
675 struct TclPass
: public Pass
{
676 TclPass() : Pass("tcl", "execute a TCL script file") { }
677 virtual void help() {
679 log(" tcl <filename>\n");
681 log("This command executes the tcl commands in the specified file.\n");
682 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
684 log("The tcl command 'yosys -import' can be used to import all yosys\n");
685 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
686 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
687 log("in order to avoid a name collision with the built in commands.\n");
690 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
692 log_cmd_error("Missing script file.\n");
694 extra_args(args
, 1, design
, false);
695 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
696 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
701 #if defined(__linux__) || defined(__CYGWIN__)
702 std::string
proc_self_dirname()
705 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
707 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
709 while (buflen
> 0 && path
[buflen
-1] != '/')
711 return std::string(path
, buflen
);
713 #elif defined(__FreeBSD__)
714 std::string
proc_self_dirname()
716 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
720 if (sysctl(mib
, 4, NULL
, &buflen
, NULL
, 0) != 0)
721 log_error("sysctl failed: %s\n", strerror(errno
));
722 buffer
= (char*)malloc(buflen
);
724 log_error("malloc failed: %s\n", strerror(errno
));
725 if (sysctl(mib
, 4, buffer
, &buflen
, NULL
, 0) != 0)
726 log_error("sysctl failed: %s\n", strerror(errno
));
727 while (buflen
> 0 && buffer
[buflen
-1] != '/')
729 path
.assign(buffer
, buflen
);
733 #elif defined(__APPLE__)
734 std::string
proc_self_dirname()
738 while (_NSGetExecutablePath(path
, &buflen
) != 0)
739 path
= (char *) realloc((void *) path
, buflen
);
740 while (buflen
> 0 && path
[buflen
-1] != '/')
742 return std::string(path
, buflen
);
744 #elif defined(_WIN32)
745 std::string
proc_self_dirname()
749 char longpath
[MAX_PATH
+ 1];
750 char shortpath
[MAX_PATH
+ 1];
752 WCHAR longpath
[MAX_PATH
+ 1];
753 TCHAR shortpath
[MAX_PATH
+ 1];
755 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
756 log_error("GetModuleFileName() failed.\n");
757 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
758 log_error("GetShortPathName() failed.\n");
759 while (shortpath
[i
] != 0)
761 while (i
> 0 && shortpath
[i
-1] != '/' && shortpath
[i
-1] != '\\')
764 for (i
= 0; shortpath
[i
]; i
++)
765 path
+= char(shortpath
[i
]);
768 #elif defined(EMSCRIPTEN)
769 std::string
proc_self_dirname()
774 #error Dont know how to determine process executable base path!
778 std::string
proc_share_dirname()
783 std::string
proc_share_dirname()
785 std::string proc_self_path
= proc_self_dirname();
786 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
787 std::string proc_share_path
= proc_self_path
+ "share\\";
788 if (check_file_exists(proc_share_path
, true))
789 return proc_share_path
;
790 proc_share_path
= proc_self_path
+ "..\\share\\";
791 if (check_file_exists(proc_share_path
, true))
792 return proc_share_path
;
794 std::string proc_share_path
= proc_self_path
+ "share/";
795 if (check_file_exists(proc_share_path
, true))
796 return proc_share_path
;
797 proc_share_path
= proc_self_path
+ "../share/yosys/";
798 if (check_file_exists(proc_share_path
, true))
799 return proc_share_path
;
801 proc_share_path
= YOSYS_DATDIR
"/";
802 if (check_file_exists(proc_share_path
, true))
803 return proc_share_path
;
806 log_error("proc_share_dirname: unable to determine share/ directory!\n");
810 bool fgetline(FILE *f
, std::string
&buffer
)
815 if (fgets(block
, 4096, f
) == NULL
)
818 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
819 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
820 buffer
.resize(buffer
.size()-1);
826 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
831 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
834 if (pos
< GetSize(command
) && command
[pos
] == '#')
837 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
838 label
+= command
[pos
++];
840 if (label
.back() == ':' && GetSize(label
) > 1)
842 label
= label
.substr(0, GetSize(label
)-1);
843 command
= command
.substr(pos
);
845 if (label
== run_from
)
846 from_to_active
= true;
847 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
848 from_to_active
= false;
852 void run_frontend(std::string filename
, std::string command
, std::string
*backend_command
, std::string
*from_to_label
, RTLIL::Design
*design
)
854 if (design
== nullptr)
855 design
= yosys_design
;
857 if (command
== "auto") {
858 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
860 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
861 command
= "verilog -sv";
862 else if (filename
.size() > 2 && filename
.substr(filename
.size()-4) == ".vhd")
864 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".blif")
866 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".json")
868 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
870 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
872 else if (filename
.size() > 2 && filename
.substr(filename
.size()-4) == ".tcl")
874 else if (filename
== "-")
877 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
880 if (command
== "script")
882 std::string run_from
, run_to
;
883 bool from_to_active
= true;
885 if (from_to_label
!= NULL
) {
886 size_t pos
= from_to_label
->find(':');
887 if (pos
== std::string::npos
) {
888 run_from
= *from_to_label
;
889 run_to
= *from_to_label
;
891 run_from
= from_to_label
->substr(0, pos
);
892 run_to
= from_to_label
->substr(pos
+1);
894 from_to_active
= run_from
.empty();
897 log("\n-- Executing script file `%s' --\n", filename
.c_str());
901 if (filename
!= "-") {
902 f
= fopen(filename
.c_str(), "r");
903 yosys_input_files
.insert(filename
);
907 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
909 FILE *backup_script_file
= Frontend::current_script_file
;
910 Frontend::current_script_file
= f
;
914 while (fgetline(f
, command
)) {
915 while (!command
.empty() && command
[command
.size()-1] == '\\') {
916 std::string next_line
;
917 if (!fgetline(f
, next_line
))
919 command
.resize(command
.size()-1);
920 command
+= next_line
;
922 handle_label(command
, from_to_active
, run_from
, run_to
);
924 Pass::call(design
, command
);
927 if (!command
.empty()) {
928 handle_label(command
, from_to_active
, run_from
, run_to
);
930 Pass::call(design
, command
);
934 Frontend::current_script_file
= backup_script_file
;
938 Frontend::current_script_file
= backup_script_file
;
943 if (backend_command
!= NULL
&& *backend_command
== "auto")
944 *backend_command
= "";
949 if (filename
== "-") {
950 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
952 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
955 if (command
== "tcl")
956 Pass::call(design
, vector
<string
>({command
, filename
}));
958 Frontend::frontend_call(design
, NULL
, filename
, command
);
961 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
)
963 run_frontend(filename
, command
, nullptr, nullptr, design
);
966 void run_pass(std::string command
, RTLIL::Design
*design
)
968 if (design
== nullptr)
969 design
= yosys_design
;
971 log("\n-- Running command `%s' --\n", command
.c_str());
973 Pass::call(design
, command
);
976 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
978 if (design
== nullptr)
979 design
= yosys_design
;
981 if (command
== "auto") {
982 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
984 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
986 else if (filename
.size() > 4 && filename
.substr(filename
.size()-4) == ".aig")
988 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
990 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".edif")
992 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".json")
994 else if (filename
== "-")
996 else if (filename
.empty())
999 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
1002 if (filename
.empty())
1005 if (filename
== "-") {
1006 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
1008 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
1011 Backend::backend_call(design
, NULL
, filename
, command
);
1014 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1015 static char *readline_cmd_generator(const char *text
, int state
)
1017 static std::map
<std::string
, Pass
*>::iterator it
;
1021 it
= pass_register
.begin();
1025 for (; it
!= pass_register
.end(); it
++) {
1026 if (it
->first
.substr(0, len
) == text
)
1027 return strdup((it
++)->first
.c_str());
1032 static char *readline_obj_generator(const char *text
, int state
)
1034 static std::vector
<char*> obj_names
;
1042 RTLIL::Design
*design
= yosys_get_design();
1043 int len
= strlen(text
);
1045 if (design
->selected_active_module
.empty())
1047 for (auto &it
: design
->modules_
)
1048 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1049 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1052 if (design
->modules_
.count(design
->selected_active_module
) > 0)
1054 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
1056 for (auto &it
: module
->wires_
)
1057 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1058 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1060 for (auto &it
: module
->memories
)
1061 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1062 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1064 for (auto &it
: module
->cells_
)
1065 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1066 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1068 for (auto &it
: module
->processes
)
1069 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1070 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1073 std::sort(obj_names
.begin(), obj_names
.end());
1076 if (idx
< obj_names
.size())
1077 return strdup(obj_names
[idx
++]);
1084 static char **readline_completion(const char *text
, int start
, int)
1087 return rl_completion_matches(text
, readline_cmd_generator
);
1088 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
1089 return rl_completion_matches(text
, readline_obj_generator
);
1094 void shell(RTLIL::Design
*design
)
1096 static int recursion_counter
= 0;
1098 recursion_counter
++;
1099 log_cmd_error_throw
= true;
1101 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1102 rl_readline_name
= (char*)"yosys";
1103 rl_attempted_completion_function
= readline_completion
;
1104 rl_basic_word_break_characters
= (char*)" \t\n";
1107 char *command
= NULL
;
1108 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1109 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
1112 char command_buffer
[4096];
1115 fputs(create_prompt(design
, recursion_counter
), stdout
);
1117 if ((command
= fgets(command_buffer
, 4096, stdin
)) == NULL
)
1120 if (command
[strspn(command
, " \t\r\n")] == 0)
1122 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1123 add_history(command
);
1126 char *p
= command
+ strspn(command
, " \t\r\n");
1127 if (!strncmp(p
, "exit", 4)) {
1129 p
+= strspn(p
, " \t\r\n");
1135 log_assert(design
->selection_stack
.size() == 1);
1136 Pass::call(design
, command
);
1137 } catch (log_cmd_error_exception
) {
1138 while (design
->selection_stack
.size() > 1)
1139 design
->selection_stack
.pop_back();
1143 if (command
== NULL
)
1146 recursion_counter
--;
1147 log_cmd_error_throw
= false;
1150 struct ShellPass
: public Pass
{
1151 ShellPass() : Pass("shell", "enter interactive command mode") { }
1152 virtual void help() {
1156 log("This command enters the interactive command mode. This can be useful\n");
1157 log("in a script to interrupt the script at a certain point and allow for\n");
1158 log("interactive inspection or manual synthesis of the design at this point.\n");
1160 log("The command prompt of the interactive shell indicates the current\n");
1161 log("selection (see 'help select'):\n");
1164 log(" the entire design is selected\n");
1167 log(" only part of the design is selected\n");
1169 log(" yosys [modname]>\n");
1170 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1172 log(" yosys [modname]*>\n");
1173 log(" only part of current module 'modname' is selected\n");
1175 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1176 log("do not terminate yosys but return to the command prompt.\n");
1178 log("This command is the default action if nothing else has been specified\n");
1179 log("on the command line.\n");
1181 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1184 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1185 extra_args(args
, 1, design
, false);
1190 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1191 struct HistoryPass
: public Pass
{
1192 HistoryPass() : Pass("history", "show last interactive commands") { }
1193 virtual void help() {
1197 log("This command prints all commands in the shell history buffer. This are\n");
1198 log("all commands executed in an interactive session, but not the commands\n");
1199 log("from executed scripts.\n");
1202 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1203 extra_args(args
, 1, design
, false);
1204 #ifdef YOSYS_ENABLE_READLINE
1205 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
1206 log("%s\n", (*list
)->line
);
1208 for (int i
= where_history(); history_get(i
); i
++)
1209 log("%s\n", history_get(i
)->line
);
1215 struct ScriptCmdPass
: public Pass
{
1216 ScriptCmdPass() : Pass("script", "execute commands from script file") { }
1217 virtual void help() {
1219 log(" script <filename> [<from_label>:<to_label>]\n");
1221 log("This command executes the yosys commands in the specified file.\n");
1223 log("The 2nd argument can be used to only execute the section of the\n");
1224 log("file between the specified labels. An empty from label is synonymous\n");
1225 log("for the beginning of the file and an empty to label is synonymous\n");
1226 log("for the end of the file.\n");
1228 log("If only one label is specified (without ':') then only the block\n");
1229 log("marked with that label (until the next label) is executed.\n");
1232 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1233 if (args
.size() < 2)
1234 log_cmd_error("Missing script file.\n");
1235 else if (args
.size() == 2)
1236 run_frontend(args
[1], "script", design
);
1237 else if (args
.size() == 3)
1238 run_frontend(args
[1], "script", NULL
, &args
[2], design
);
1240 extra_args(args
, 2, design
, false);