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>
47 # include <sys/types.h>
48 # include <sys/stat.h>
49 # if !defined(YOSYS_DISABLE_SPAWN)
50 # include <sys/wait.h>
54 #if !defined(_WIN32) && defined(YOSYS_ENABLE_GLOB)
59 # include <sys/sysctl.h>
63 #if PY_MAJOR_VERSION >= 3
64 # define INIT_MODULE PyInit_libyosys
65 extern "C" PyObject
* INIT_MODULE();
67 # define INIT_MODULE initlibyosys
68 extern "C" void INIT_MODULE();
79 RTLIL::Design
*yosys_design
= NULL
;
80 CellTypes yosys_celltypes
;
82 #ifdef YOSYS_ENABLE_TCL
83 Tcl_Interp
*yosys_tcl_interp
= NULL
;
86 std::set
<std::string
> yosys_input_files
, yosys_output_files
;
88 bool memhasher_active
= false;
89 uint32_t memhasher_rng
= 123456;
90 std::vector
<void*> memhasher_store
;
94 #if defined(__linux__) || defined(__FreeBSD__)
95 memhasher_rng
+= time(NULL
) << 16 ^ getpid();
97 memhasher_store
.resize(0x10000);
98 memhasher_active
= true;
103 for (auto p
: memhasher_store
)
105 memhasher_store
.clear();
106 memhasher_active
= false;
111 memhasher_rng
^= memhasher_rng
<< 13;
112 memhasher_rng
^= memhasher_rng
>> 17;
113 memhasher_rng
^= memhasher_rng
<< 5;
115 int size
, index
= (memhasher_rng
>> 4) & 0xffff;
116 switch (memhasher_rng
& 7) {
117 case 0: size
= 16; break;
118 case 1: size
= 256; break;
119 case 2: size
= 1024; break;
120 case 3: size
= 4096; break;
123 if (index
< 16) size
*= 16;
124 memhasher_store
[index
] = realloc(memhasher_store
[index
], size
);
130 log(" /----------------------------------------------------------------------------\\\n");
132 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
134 log(" | Copyright (C) 2012 - 2020 Claire Wolf <claire@symbioticeda.com> |\n");
136 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
137 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
138 log(" | copyright notice and this permission notice appear in all copies. |\n");
140 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
141 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
142 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
143 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
144 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
145 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
146 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
148 log(" \\----------------------------------------------------------------------------/\n");
150 log(" %s\n", yosys_version_str
);
156 #if defined(__GNUC__)
157 return x
> 1 ? (8*sizeof(int)) - __builtin_clz(x
-1) : 0;
161 for (int i
= 0; i
< 32; i
++)
162 if (((x
-1) >> i
) == 0)
168 std::string
stringf(const char *fmt
, ...)
174 string
= vstringf(fmt
, ap
);
180 std::string
vstringf(const char *fmt
, va_list ap
)
185 #if defined(_WIN32 )|| defined(__CYGWIN__)
190 str
= (char*)realloc(str
, sz
);
191 rc
= vsnprintf(str
, sz
, fmt
, apc
);
193 if (rc
>= 0 && rc
< sz
)
198 if (vasprintf(&str
, fmt
, ap
) < 0)
210 int readsome(std::istream
&f
, char *s
, int n
)
212 int rc
= int(f
.readsome(s
, n
));
214 // f.readsome() sometimes returns 0 on a non-empty stream..
226 std::string
next_token(std::string
&text
, const char *sep
, bool long_strings
)
228 size_t pos_begin
= text
.find_first_not_of(sep
);
230 if (pos_begin
== std::string::npos
)
231 pos_begin
= text
.size();
233 if (long_strings
&& pos_begin
!= text
.size() && text
[pos_begin
] == '"') {
234 string sep_string
= sep
;
235 for (size_t i
= pos_begin
+1; i
< text
.size(); i
++) {
236 if (text
[i
] == '"' && (i
+1 == text
.size() || sep_string
.find(text
[i
+1]) != std::string::npos
)) {
237 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
238 text
= text
.substr(i
+1);
241 if (i
+1 < text
.size() && text
[i
] == '"' && text
[i
+1] == ';' && (i
+2 == text
.size() || sep_string
.find(text
[i
+2]) != std::string::npos
)) {
242 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
243 text
= text
.substr(i
+2);
249 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
251 if (pos_end
== std::string::npos
)
252 pos_end
= text
.size();
254 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
255 text
= text
.substr(pos_end
);
259 std::vector
<std::string
> split_tokens(const std::string
&text
, const char *sep
)
261 std::vector
<std::string
> tokens
;
262 std::string current_token
;
263 for (char c
: text
) {
264 if (strchr(sep
, c
)) {
265 if (!current_token
.empty()) {
266 tokens
.push_back(current_token
);
267 current_token
.clear();
272 if (!current_token
.empty()) {
273 tokens
.push_back(current_token
);
274 current_token
.clear();
279 // this is very similar to fnmatch(). the exact rules used by this
282 // ? matches any character except
283 // * matches any sequence of characters
284 // [...] matches any of the characters in the list
285 // [!..] matches any of the characters not in the list
287 // a backslash may be used to escape the next characters in the
288 // pattern. each special character can also simply match itself.
290 bool patmatch(const char *pattern
, const char *string
)
295 if (*pattern
== '\\') {
296 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
300 if (*pattern
== '?') {
303 return patmatch(pattern
+1, string
+1);
306 if (*pattern
== '*') {
308 if (patmatch(pattern
+1, string
++))
311 return pattern
[1] == 0;
314 if (*pattern
== '[') {
315 bool found_match
= false;
316 bool inverted_list
= pattern
[1] == '!';
317 const char *p
= pattern
+ (inverted_list
? 1 : 0);
321 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
335 if (*pattern
== *string
)
336 return patmatch(pattern
+1, string
+1);
341 #if !defined(YOSYS_DISABLE_SPAWN)
342 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
345 return system(command
.c_str());
347 FILE *f
= popen(command
.c_str(), "r");
353 while (fgets(logbuf
, 128, f
) != NULL
) {
355 if (!line
.empty() && line
.back() == '\n')
356 process_line(line
), line
.clear();
367 return WEXITSTATUS(ret
);
372 std::string
make_temp_file(std::string template_str
)
375 size_t pos
= template_str
.rfind("XXXXXX");
376 log_assert(pos
!= std::string::npos
);
377 static size_t index
= 0;
378 template_str
.replace(pos
, 6, stringf("%06zu", index
++));
379 #elif defined(_WIN32)
380 if (template_str
.rfind("/tmp/", 0) == 0) {
382 char longpath
[MAX_PATH
+ 1];
383 char shortpath
[MAX_PATH
+ 1];
385 WCHAR longpath
[MAX_PATH
+ 1];
386 TCHAR shortpath
[MAX_PATH
+ 1];
388 if (!GetTempPath(MAX_PATH
+1, longpath
))
389 log_error("GetTempPath() failed.\n");
390 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+ 1))
391 log_error("GetShortPathName() failed.\n");
393 for (int i
= 0; shortpath
[i
]; i
++)
394 path
+= char(shortpath
[i
]);
395 template_str
= stringf("%s\\%s", path
.c_str(), template_str
.c_str() + 5);
398 size_t pos
= template_str
.rfind("XXXXXX");
399 log_assert(pos
!= std::string::npos
);
402 for (int i
= 0; i
< 6; i
++) {
403 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
404 static uint32_t x
= 314159265 ^ uint32_t(time(NULL
));
405 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
406 template_str
[pos
+i
] = y
[x
% y
.size()];
408 if (_access(template_str
.c_str(), 0) != 0)
412 size_t pos
= template_str
.rfind("XXXXXX");
413 log_assert(pos
!= std::string::npos
);
415 int suffixlen
= GetSize(template_str
) - pos
- 6;
417 char *p
= strdup(template_str
.c_str());
418 close(mkstemps(p
, suffixlen
));
426 std::string
make_temp_dir(std::string template_str
)
429 template_str
= make_temp_file(template_str
);
430 mkdir(template_str
.c_str());
432 #elif defined(__wasm)
433 template_str
= make_temp_file(template_str
);
434 mkdir(template_str
.c_str(), 0777);
438 size_t pos
= template_str
.rfind("XXXXXX");
439 log_assert(pos
!= std::string::npos
);
441 int suffixlen
= GetSize(template_str
) - pos
- 6;
442 log_assert(suffixlen
== 0);
445 char *p
= strdup(template_str
.c_str());
447 log_assert(p
!= NULL
);
456 bool check_file_exists(std::string filename
, bool)
458 return _access(filename
.c_str(), 0) == 0;
461 bool check_file_exists(std::string filename
, bool is_exec
)
463 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
467 bool is_absolute_path(std::string filename
)
470 return filename
[0] == '/' || filename
[0] == '\\' || (filename
[0] != 0 && filename
[1] == ':');
472 return filename
[0] == '/';
476 void remove_directory(std::string dirname
)
479 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
482 struct dirent
**namelist
;
483 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
485 for (int i
= 0; i
< n
; i
++) {
486 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
487 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
488 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
489 remove(buffer
.c_str());
491 remove_directory(buffer
);
496 rmdir(dirname
.c_str());
500 std::string
escape_filename_spaces(const std::string
& filename
)
503 out
.reserve(filename
.size());
504 for (auto c
: filename
)
514 int GetSize(RTLIL::Wire
*wire
)
519 bool already_setup
= false;
525 already_setup
= true;
527 #define X(_id) RTLIL::ID::_id = "\\" # _id;
528 #include "kernel/constids.inc"
532 PyImport_AppendInittab((char*)"libyosys", INIT_MODULE
);
534 PyRun_SimpleString("import sys");
537 Pass::init_register();
538 yosys_design
= new RTLIL::Design
;
539 yosys_celltypes
.setup();
543 bool yosys_already_setup()
545 return already_setup
;
548 bool already_shutdown
= false;
550 void yosys_shutdown()
554 already_shutdown
= true;
557 Pass::done_register();
562 for (auto f
: log_files
)
568 yosys_celltypes
.clear();
570 #ifdef YOSYS_ENABLE_TCL
571 if (yosys_tcl_interp
!= NULL
) {
572 Tcl_DeleteInterp(yosys_tcl_interp
);
574 yosys_tcl_interp
= NULL
;
578 #ifdef YOSYS_ENABLE_PLUGINS
579 for (auto &it
: loaded_plugins
)
582 loaded_plugins
.clear();
584 loaded_python_plugins
.clear();
586 loaded_plugin_aliases
.clear();
594 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
597 size_t pos
= file
.find_last_of("/\\");
599 size_t pos
= file
.find_last_of('/');
601 if (pos
!= std::string::npos
)
602 file
= file
.substr(pos
+1);
604 pos
= func
.find_last_of(':');
605 if (pos
!= std::string::npos
)
606 func
= func
.substr(pos
+1);
608 return stringf("$auto$%s:%d:%s$%d", file
.c_str(), line
, func
.c_str(), autoidx
++);
611 RTLIL::Design
*yosys_get_design()
616 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
618 static char buffer
[100];
619 std::string str
= "\n";
620 if (recursion_counter
> 1)
621 str
+= stringf("(%d) ", recursion_counter
);
623 if (!design
->selected_active_module
.empty())
624 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
625 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
626 if (design
->selected_active_module
.empty())
628 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
629 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
632 snprintf(buffer
, 100, "%s> ", str
.c_str());
636 std::vector
<std::string
> glob_filename(const std::string
&filename_pattern
)
638 std::vector
<std::string
> results
;
640 #if defined(_WIN32) || !defined(YOSYS_ENABLE_GLOB)
641 results
.push_back(filename_pattern
);
645 int err
= glob(filename_pattern
.c_str(), 0, NULL
, &globbuf
);
648 for (size_t i
= 0; i
< globbuf
.gl_pathc
; i
++)
649 results
.push_back(globbuf
.gl_pathv
[i
]);
652 results
.push_back(filename_pattern
);
659 void rewrite_filename(std::string
&filename
)
661 if (filename
.compare(0, 1, "\"") == 0 && filename
.compare(GetSize(filename
)-1, std::string::npos
, "\"") == 0)
662 filename
= filename
.substr(1, GetSize(filename
)-2);
663 if (filename
.compare(0, 2, "+/") == 0)
664 filename
= proc_share_dirname() + filename
.substr(2);
666 if (filename
.compare(0, 2, "~/") == 0)
667 filename
= filename
.replace(0, 1, getenv("HOME"));
671 #ifdef YOSYS_ENABLE_TCL
672 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
674 std::vector
<std::string
> args
;
675 for (int i
= 1; i
< argc
; i
++)
676 args
.push_back(argv
[i
]);
678 if (args
.size() >= 1 && args
[0] == "-import") {
679 for (auto &it
: pass_register
) {
680 std::string tcl_command_name
= it
.first
;
681 if (tcl_command_name
== "proc")
682 tcl_command_name
= "procs";
683 else if (tcl_command_name
== "rename")
684 tcl_command_name
= "renames";
686 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
687 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
689 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
690 Tcl_Eval(interp
, tcl_script
.c_str());
696 if (args
.size() == 1) {
697 Pass::call(yosys_get_design(), args
[0]);
701 Pass::call(yosys_get_design(), args
);
705 extern Tcl_Interp
*yosys_get_tcl_interp()
707 if (yosys_tcl_interp
== NULL
) {
708 yosys_tcl_interp
= Tcl_CreateInterp();
709 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
711 return yosys_tcl_interp
;
714 struct TclPass
: public Pass
{
715 TclPass() : Pass("tcl", "execute a TCL script file") { }
716 void help() override
{
717 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
719 log(" tcl <filename> [args]\n");
721 log("This command executes the tcl commands in the specified file.\n");
722 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
724 log("The tcl command 'yosys -import' can be used to import all yosys\n");
725 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
726 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
727 log("in order to avoid a name collision with the built in commands.\n");
729 log("If any arguments are specified, these arguments are provided to the script via\n");
730 log("the standard $argc and $argv variables.\n");
733 void execute(std::vector
<std::string
> args
, RTLIL::Design
*) override
{
735 log_cmd_error("Missing script file.\n");
737 std::vector
<Tcl_Obj
*> script_args
;
738 for (auto it
= args
.begin() + 2; it
!= args
.end(); ++it
)
739 script_args
.push_back(Tcl_NewStringObj((*it
).c_str(), (*it
).size()));
741 Tcl_Interp
*interp
= yosys_get_tcl_interp();
742 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argc", 4), NULL
, Tcl_NewIntObj(script_args
.size()), 0);
743 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv", 4), NULL
, Tcl_NewListObj(script_args
.size(), script_args
.data()), 0);
744 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv0", 5), NULL
, Tcl_NewStringObj(args
[1].c_str(), args
[1].size()), 0);
745 if (Tcl_EvalFile(interp
, args
[1].c_str()) != TCL_OK
)
746 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp
));
751 #if defined(__linux__) || defined(__CYGWIN__)
752 std::string
proc_self_dirname()
755 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
757 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
759 while (buflen
> 0 && path
[buflen
-1] != '/')
761 return std::string(path
, buflen
);
763 #elif defined(__FreeBSD__)
764 std::string
proc_self_dirname()
766 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
770 if (sysctl(mib
, 4, NULL
, &buflen
, NULL
, 0) != 0)
771 log_error("sysctl failed: %s\n", strerror(errno
));
772 buffer
= (char*)malloc(buflen
);
774 log_error("malloc failed: %s\n", strerror(errno
));
775 if (sysctl(mib
, 4, buffer
, &buflen
, NULL
, 0) != 0)
776 log_error("sysctl failed: %s\n", strerror(errno
));
777 while (buflen
> 0 && buffer
[buflen
-1] != '/')
779 path
.assign(buffer
, buflen
);
783 #elif defined(__APPLE__)
784 std::string
proc_self_dirname()
788 while (_NSGetExecutablePath(path
, &buflen
) != 0)
789 path
= (char *) realloc((void *) path
, buflen
);
790 while (buflen
> 0 && path
[buflen
-1] != '/')
792 return std::string(path
, buflen
);
794 #elif defined(_WIN32)
795 std::string
proc_self_dirname()
799 char longpath
[MAX_PATH
+ 1];
800 char shortpath
[MAX_PATH
+ 1];
802 WCHAR longpath
[MAX_PATH
+ 1];
803 TCHAR shortpath
[MAX_PATH
+ 1];
805 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
806 log_error("GetModuleFileName() failed.\n");
807 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
808 log_error("GetShortPathName() failed.\n");
809 while (shortpath
[i
] != 0)
811 while (i
> 0 && shortpath
[i
-1] != '/' && shortpath
[i
-1] != '\\')
814 for (i
= 0; shortpath
[i
]; i
++)
815 path
+= char(shortpath
[i
]);
818 #elif defined(EMSCRIPTEN) || defined(__wasm)
819 std::string
proc_self_dirname()
824 #error "Don't know how to determine process executable base path!"
827 #if defined(EMSCRIPTEN) || defined(__wasm)
828 std::string
proc_share_dirname()
833 std::string
proc_share_dirname()
835 std::string proc_self_path
= proc_self_dirname();
836 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
837 std::string proc_share_path
= proc_self_path
+ "share\\";
838 if (check_file_exists(proc_share_path
, true))
839 return proc_share_path
;
840 proc_share_path
= proc_self_path
+ "..\\share\\";
841 if (check_file_exists(proc_share_path
, true))
842 return proc_share_path
;
844 std::string proc_share_path
= proc_self_path
+ "share/";
845 if (check_file_exists(proc_share_path
, true))
846 return proc_share_path
;
847 proc_share_path
= proc_self_path
+ "../share/" + proc_program_prefix()+ "yosys/";
848 if (check_file_exists(proc_share_path
, true))
849 return proc_share_path
;
851 proc_share_path
= YOSYS_DATDIR
"/";
852 if (check_file_exists(proc_share_path
, true))
853 return proc_share_path
;
856 log_error("proc_share_dirname: unable to determine share/ directory!\n");
860 std::string
proc_program_prefix()
862 std::string program_prefix
;
863 #ifdef YOSYS_PROGRAM_PREFIX
864 program_prefix
= YOSYS_PROGRAM_PREFIX
;
866 return program_prefix
;
869 bool fgetline(FILE *f
, std::string
&buffer
)
874 if (fgets(block
, 4096, f
) == NULL
)
877 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
878 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
879 buffer
.resize(buffer
.size()-1);
885 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
890 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
893 if (pos
< GetSize(command
) && command
[pos
] == '#')
896 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
897 label
+= command
[pos
++];
899 if (GetSize(label
) > 1 && label
.back() == ':')
901 label
= label
.substr(0, GetSize(label
)-1);
902 command
= command
.substr(pos
);
904 if (label
== run_from
)
905 from_to_active
= true;
906 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
907 from_to_active
= false;
911 void run_frontend(std::string filename
, std::string command
, std::string
*backend_command
, std::string
*from_to_label
, RTLIL::Design
*design
)
913 if (design
== nullptr)
914 design
= yosys_design
;
916 if (command
== "auto") {
917 std::string filename_trim
= filename
;
918 if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".gz") == 0)
919 filename_trim
.erase(filename_trim
.size()-3);
920 if (filename_trim
.size() > 2 && filename_trim
.compare(filename_trim
.size()-2, std::string::npos
, ".v") == 0)
922 else if (filename_trim
.size() > 2 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".sv") == 0)
923 command
= "verilog -sv";
924 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-4, std::string::npos
, ".vhd") == 0)
926 else if (filename_trim
.size() > 4 && filename_trim
.compare(filename_trim
.size()-5, std::string::npos
, ".blif") == 0)
928 else if (filename_trim
.size() > 5 && filename_trim
.compare(filename_trim
.size()-6, std::string::npos
, ".eblif") == 0)
930 else if (filename_trim
.size() > 4 && filename_trim
.compare(filename_trim
.size()-5, std::string::npos
, ".json") == 0)
932 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".il") == 0)
934 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".ys") == 0)
936 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-4, std::string::npos
, ".tcl") == 0)
938 else if (filename
== "-")
941 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
944 if (command
== "script")
946 std::string run_from
, run_to
;
947 bool from_to_active
= true;
949 if (from_to_label
!= NULL
) {
950 size_t pos
= from_to_label
->find(':');
951 if (pos
== std::string::npos
) {
952 run_from
= *from_to_label
;
953 run_to
= *from_to_label
;
955 run_from
= from_to_label
->substr(0, pos
);
956 run_to
= from_to_label
->substr(pos
+1);
958 from_to_active
= run_from
.empty();
961 log("\n-- Executing script file `%s' --\n", filename
.c_str());
965 if (filename
!= "-") {
966 f
= fopen(filename
.c_str(), "r");
967 yosys_input_files
.insert(filename
);
971 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
973 FILE *backup_script_file
= Frontend::current_script_file
;
974 Frontend::current_script_file
= f
;
978 while (fgetline(f
, command
)) {
979 while (!command
.empty() && command
[command
.size()-1] == '\\') {
980 std::string next_line
;
981 if (!fgetline(f
, next_line
))
983 command
.resize(command
.size()-1);
984 command
+= next_line
;
986 handle_label(command
, from_to_active
, run_from
, run_to
);
987 if (from_to_active
) {
988 Pass::call(design
, command
);
993 if (!command
.empty()) {
994 handle_label(command
, from_to_active
, run_from
, run_to
);
995 if (from_to_active
) {
996 Pass::call(design
, command
);
1002 Frontend::current_script_file
= backup_script_file
;
1006 Frontend::current_script_file
= backup_script_file
;
1008 if (filename
!= "-")
1011 if (backend_command
!= NULL
&& *backend_command
== "auto")
1012 *backend_command
= "";
1017 if (filename
== "-") {
1018 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
1020 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
1023 if (command
== "tcl")
1024 Pass::call(design
, vector
<string
>({command
, filename
}));
1026 Frontend::frontend_call(design
, NULL
, filename
, command
);
1030 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
)
1032 run_frontend(filename
, command
, nullptr, nullptr, design
);
1035 void run_pass(std::string command
, RTLIL::Design
*design
)
1037 if (design
== nullptr)
1038 design
= yosys_design
;
1040 log("\n-- Running command `%s' --\n", command
.c_str());
1042 Pass::call(design
, command
);
1045 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
1047 if (design
== nullptr)
1048 design
= yosys_design
;
1050 if (command
== "auto") {
1051 if (filename
.size() > 2 && filename
.compare(filename
.size()-2, std::string::npos
, ".v") == 0)
1052 command
= "verilog";
1053 else if (filename
.size() > 3 && filename
.compare(filename
.size()-3, std::string::npos
, ".il") == 0)
1055 else if (filename
.size() > 3 && filename
.compare(filename
.size()-3, std::string::npos
, ".cc") == 0)
1057 else if (filename
.size() > 4 && filename
.compare(filename
.size()-4, std::string::npos
, ".aig") == 0)
1059 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".blif") == 0)
1061 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".edif") == 0)
1063 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".json") == 0)
1065 else if (filename
== "-")
1067 else if (filename
.empty())
1070 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
1073 if (filename
.empty())
1076 if (filename
== "-") {
1077 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
1079 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
1082 Backend::backend_call(design
, NULL
, filename
, command
);
1085 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1086 static char *readline_cmd_generator(const char *text
, int state
)
1088 static std::map
<std::string
, Pass
*>::iterator it
;
1092 it
= pass_register
.begin();
1096 for (; it
!= pass_register
.end(); it
++) {
1097 if (it
->first
.compare(0, len
, text
) == 0)
1098 return strdup((it
++)->first
.c_str());
1103 static char *readline_obj_generator(const char *text
, int state
)
1105 static std::vector
<char*> obj_names
;
1113 RTLIL::Design
*design
= yosys_get_design();
1114 int len
= strlen(text
);
1116 if (design
->selected_active_module
.empty())
1118 for (auto mod
: design
->modules())
1119 if (RTLIL::unescape_id(mod
->name
).compare(0, len
, text
) == 0)
1120 obj_names
.push_back(strdup(log_id(mod
->name
)));
1122 else if (design
->module(design
->selected_active_module
) != nullptr)
1124 RTLIL::Module
*module
= design
->module(design
->selected_active_module
);
1126 for (auto w
: module
->wires())
1127 if (RTLIL::unescape_id(w
->name
).compare(0, len
, text
) == 0)
1128 obj_names
.push_back(strdup(log_id(w
->name
)));
1130 for (auto &it
: module
->memories
)
1131 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1132 obj_names
.push_back(strdup(log_id(it
.first
)));
1134 for (auto cell
: module
->cells())
1135 if (RTLIL::unescape_id(cell
->name
).compare(0, len
, text
) == 0)
1136 obj_names
.push_back(strdup(log_id(cell
->name
)));
1138 for (auto &it
: module
->processes
)
1139 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1140 obj_names
.push_back(strdup(log_id(it
.first
)));
1143 std::sort(obj_names
.begin(), obj_names
.end());
1146 if (idx
< obj_names
.size())
1147 return strdup(obj_names
[idx
++]);
1154 static char **readline_completion(const char *text
, int start
, int)
1157 return rl_completion_matches(text
, readline_cmd_generator
);
1158 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
1159 return rl_completion_matches(text
, readline_obj_generator
);
1164 void shell(RTLIL::Design
*design
)
1166 static int recursion_counter
= 0;
1168 recursion_counter
++;
1169 log_cmd_error_throw
= true;
1171 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1172 rl_readline_name
= (char*)"yosys";
1173 rl_attempted_completion_function
= readline_completion
;
1174 rl_basic_word_break_characters
= (char*)" \t\n";
1177 char *command
= NULL
;
1178 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1179 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
1182 char command_buffer
[4096];
1185 fputs(create_prompt(design
, recursion_counter
), stdout
);
1187 if ((command
= fgets(command_buffer
, 4096, stdin
)) == NULL
)
1190 if (command
[strspn(command
, " \t\r\n")] == 0)
1192 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1193 add_history(command
);
1196 char *p
= command
+ strspn(command
, " \t\r\n");
1197 if (!strncmp(p
, "exit", 4)) {
1199 p
+= strspn(p
, " \t\r\n");
1205 log_assert(design
->selection_stack
.size() == 1);
1206 Pass::call(design
, command
);
1207 } catch (log_cmd_error_exception
) {
1208 while (design
->selection_stack
.size() > 1)
1209 design
->selection_stack
.pop_back();
1214 if (command
== NULL
)
1217 recursion_counter
--;
1218 log_cmd_error_throw
= false;
1221 struct ShellPass
: public Pass
{
1222 ShellPass() : Pass("shell", "enter interactive command mode") { }
1223 void help() override
{
1227 log("This command enters the interactive command mode. This can be useful\n");
1228 log("in a script to interrupt the script at a certain point and allow for\n");
1229 log("interactive inspection or manual synthesis of the design at this point.\n");
1231 log("The command prompt of the interactive shell indicates the current\n");
1232 log("selection (see 'help select'):\n");
1235 log(" the entire design is selected\n");
1238 log(" only part of the design is selected\n");
1240 log(" yosys [modname]>\n");
1241 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1243 log(" yosys [modname]*>\n");
1244 log(" only part of current module 'modname' is selected\n");
1246 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1247 log("do not terminate yosys but return to the command prompt.\n");
1249 log("This command is the default action if nothing else has been specified\n");
1250 log("on the command line.\n");
1252 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1255 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) override
{
1256 extra_args(args
, 1, design
, false);
1261 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1262 struct HistoryPass
: public Pass
{
1263 HistoryPass() : Pass("history", "show last interactive commands") { }
1264 void help() override
{
1268 log("This command prints all commands in the shell history buffer. This are\n");
1269 log("all commands executed in an interactive session, but not the commands\n");
1270 log("from executed scripts.\n");
1273 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) override
{
1274 extra_args(args
, 1, design
, false);
1275 #ifdef YOSYS_ENABLE_READLINE
1276 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
1277 log("%s\n", (*list
)->line
);
1279 for (int i
= where_history(); history_get(i
); i
++)
1280 log("%s\n", history_get(i
)->line
);
1286 struct ScriptCmdPass
: public Pass
{
1287 ScriptCmdPass() : Pass("script", "execute commands from file or wire") { }
1288 void help() override
{
1289 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1291 log(" script <filename> [<from_label>:<to_label>]\n");
1292 log(" script -scriptwire [selection]\n");
1294 log("This command executes the yosys commands in the specified file (default\n");
1295 log("behaviour), or commands embedded in the constant text value connected to the\n");
1296 log("selected wires.\n");
1298 log("In the default (file) case, the 2nd argument can be used to only execute the\n");
1299 log("section of the file between the specified labels. An empty from label is\n");
1300 log("synonymous with the beginning of the file and an empty to label is synonymous\n");
1301 log("with the end of the file.\n");
1303 log("If only one label is specified (without ':') then only the block\n");
1304 log("marked with that label (until the next label) is executed.\n");
1306 log("In \"-scriptwire\" mode, the commands on the selected wire(s) will be executed\n");
1307 log("in the scope of (and thus, relative to) the wires' owning module(s). This\n");
1308 log("'-module' mode can be exited by using the 'cd' command.\n");
1311 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) override
1313 bool scriptwire
= false;
1316 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
1317 if (args
[argidx
] == "-scriptwire") {
1324 extra_args(args
, argidx
, design
);
1326 for (auto mod
: design
->selected_modules())
1327 for (auto &c
: mod
->connections()) {
1328 if (!c
.first
.is_wire())
1330 auto w
= c
.first
.as_wire();
1331 if (!mod
->selected(w
))
1333 if (!c
.second
.is_fully_const())
1334 log_error("RHS of selected wire %s.%s is not constant.\n", log_id(mod
), log_id(w
));
1335 auto v
= c
.second
.as_const();
1336 Pass::call_on_module(design
, mod
, v
.decode_string());
1339 else if (args
.size() < 2)
1340 log_cmd_error("Missing script file.\n");
1341 else if (args
.size() == 2)
1342 run_frontend(args
[1], "script", design
);
1343 else if (args
.size() == 3)
1344 run_frontend(args
[1], "script", NULL
, &args
[2], design
);
1346 extra_args(args
, 2, design
, false);