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/stat.h>
60 RTLIL::Design
*yosys_design
= NULL
;
61 CellTypes yosys_celltypes
;
63 #ifdef YOSYS_ENABLE_TCL
64 Tcl_Interp
*yosys_tcl_interp
= NULL
;
67 bool memhasher_active
= false;
68 uint32_t memhasher_rng
= 123456;
69 std::vector
<void*> memhasher_store
;
74 memhasher_rng
+= time(NULL
) << 16 ^ getpid();
76 memhasher_store
.resize(0x10000);
77 memhasher_active
= true;
82 for (auto p
: memhasher_store
)
84 memhasher_store
.clear();
85 memhasher_active
= false;
90 memhasher_rng
^= memhasher_rng
<< 13;
91 memhasher_rng
^= memhasher_rng
>> 17;
92 memhasher_rng
^= memhasher_rng
<< 5;
94 int size
, index
= (memhasher_rng
>> 4) & 0xffff;
95 switch (memhasher_rng
& 7) {
96 case 0: size
= 16; break;
97 case 1: size
= 256; break;
98 case 2: size
= 1024; break;
99 case 3: size
= 4096; break;
102 if (index
< 16) size
*= 16;
103 memhasher_store
[index
] = realloc(memhasher_store
[index
], size
);
109 log(" /----------------------------------------------------------------------------\\\n");
111 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
113 log(" | Copyright (C) 2012 - 2016 Clifford Wolf <clifford@clifford.at> |\n");
115 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
116 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
117 log(" | copyright notice and this permission notice appear in all copies. |\n");
119 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
120 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
121 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
122 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
123 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
124 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
125 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
127 log(" \\----------------------------------------------------------------------------/\n");
129 log(" %s\n", yosys_version_str
);
138 for (int i
= 0; i
< 32; i
++)
139 if (((x
-1) >> i
) == 0)
145 std::string
stringf(const char *fmt
, ...)
151 string
= vstringf(fmt
, ap
);
157 std::string
vstringf(const char *fmt
, va_list ap
)
167 str
= (char*)realloc(str
, sz
);
168 rc
= vsnprintf(str
, sz
, fmt
, apc
);
170 if (rc
>= 0 && rc
< sz
)
175 if (vasprintf(&str
, fmt
, ap
) < 0)
187 int readsome(std::istream
&f
, char *s
, int n
)
189 int rc
= int(f
.readsome(s
, n
));
191 // f.readsome() sometimes returns 0 on a non-empty stream..
203 std::string
next_token(std::string
&text
, const char *sep
, bool long_strings
)
205 size_t pos_begin
= text
.find_first_not_of(sep
);
207 if (pos_begin
== std::string::npos
)
208 pos_begin
= text
.size();
210 if (long_strings
&& pos_begin
!= text
.size() && text
[pos_begin
] == '"') {
211 string sep_string
= sep
;
212 for (size_t i
= pos_begin
+1; i
< text
.size(); i
++)
213 if (text
[i
] == '"' && (i
+1 == text
.size() || sep_string
.find(text
[i
+1]) != std::string::npos
)) {
214 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
215 text
= text
.substr(i
+1);
220 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
222 if (pos_end
== std::string::npos
)
223 pos_end
= text
.size();
225 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
226 text
= text
.substr(pos_end
);
230 std::vector
<std::string
> split_tokens(const std::string
&text
, const char *sep
)
232 std::vector
<std::string
> tokens
;
233 std::string current_token
;
234 for (char c
: text
) {
235 if (strchr(sep
, c
)) {
236 if (!current_token
.empty()) {
237 tokens
.push_back(current_token
);
238 current_token
.clear();
243 if (!current_token
.empty()) {
244 tokens
.push_back(current_token
);
245 current_token
.clear();
250 // this is very similar to fnmatch(). the exact rules used by this
253 // ? matches any character except
254 // * matches any sequence of characters
255 // [...] matches any of the characters in the list
256 // [!..] matches any of the characters not in the list
258 // a backslash may be used to escape the next characters in the
259 // pattern. each special character can also simply match itself.
261 bool patmatch(const char *pattern
, const char *string
)
266 if (*pattern
== '\\') {
267 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
271 if (*pattern
== '?') {
274 return patmatch(pattern
+1, string
+1);
277 if (*pattern
== '*') {
279 if (patmatch(pattern
+1, string
++))
282 return pattern
[1] == 0;
285 if (*pattern
== '[') {
286 bool found_match
= false;
287 bool inverted_list
= pattern
[1] == '!';
288 const char *p
= pattern
+ (inverted_list
? 1 : 0);
292 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
306 if (*pattern
== *string
)
307 return patmatch(pattern
+1, string
+1);
312 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
315 return system(command
.c_str());
317 FILE *f
= popen(command
.c_str(), "r");
323 while (fgets(logbuf
, 128, f
) != NULL
) {
325 if (!line
.empty() && line
.back() == '\n')
326 process_line(line
), line
.clear();
337 return WEXITSTATUS(ret
);
341 std::string
make_temp_file(std::string template_str
)
344 if (template_str
.rfind("/tmp/", 0) == 0) {
346 char longpath
[MAX_PATH
+ 1];
347 char shortpath
[MAX_PATH
+ 1];
349 WCHAR longpath
[MAX_PATH
+ 1];
350 TCHAR shortpath
[MAX_PATH
+ 1];
352 if (!GetTempPath(MAX_PATH
+1, longpath
))
353 log_error("GetTempPath() failed.\n");
354 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+ 1))
355 log_error("GetShortPathName() failed.\n");
357 for (int i
= 0; shortpath
[i
]; i
++)
358 path
+= char(shortpath
[i
]);
359 template_str
= stringf("%s\\%s", path
.c_str(), template_str
.c_str() + 5);
362 size_t pos
= template_str
.rfind("XXXXXX");
363 log_assert(pos
!= std::string::npos
);
366 for (int i
= 0; i
< 6; i
++) {
367 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
368 static uint32_t x
= 314159265 ^ uint32_t(time(NULL
));
369 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
370 template_str
[pos
+i
] = y
[x
% y
.size()];
372 if (_access(template_str
.c_str(), 0) != 0)
376 size_t pos
= template_str
.rfind("XXXXXX");
377 log_assert(pos
!= std::string::npos
);
379 int suffixlen
= GetSize(template_str
) - pos
- 6;
381 char *p
= strdup(template_str
.c_str());
382 close(mkstemps(p
, suffixlen
));
390 std::string
make_temp_dir(std::string template_str
)
393 template_str
= make_temp_file(template_str
);
394 mkdir(template_str
.c_str());
398 size_t pos
= template_str
.rfind("XXXXXX");
399 log_assert(pos
!= std::string::npos
);
401 int suffixlen
= GetSize(template_str
) - pos
- 6;
402 log_assert(suffixlen
== 0);
405 char *p
= strdup(template_str
.c_str());
407 log_assert(p
!= NULL
);
416 bool check_file_exists(std::string filename
, bool)
418 return _access(filename
.c_str(), 0) == 0;
421 bool check_file_exists(std::string filename
, bool is_exec
)
423 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
427 bool is_absolute_path(std::string filename
)
430 return filename
[0] == '/' || filename
[0] == '\\' || (filename
[0] != 0 && filename
[1] == ':');
432 return filename
[0] == '/';
436 void remove_directory(std::string dirname
)
439 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
442 struct dirent
**namelist
;
443 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
445 for (int i
= 0; i
< n
; i
++) {
446 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
447 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
448 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
449 remove(buffer
.c_str());
451 remove_directory(buffer
);
456 rmdir(dirname
.c_str());
460 int GetSize(RTLIL::Wire
*wire
)
467 // if there are already IdString objects then we have a global initialization order bug
469 log_assert(empty_id
.index_
== 0);
470 IdString::get_reference(empty_id
.index_
);
472 Pass::init_register();
473 yosys_design
= new RTLIL::Design
;
474 yosys_celltypes
.setup();
478 void yosys_shutdown()
485 for (auto f
: log_files
)
491 Pass::done_register();
492 yosys_celltypes
.clear();
494 #ifdef YOSYS_ENABLE_TCL
495 if (yosys_tcl_interp
!= NULL
) {
496 Tcl_DeleteInterp(yosys_tcl_interp
);
498 yosys_tcl_interp
= NULL
;
502 #ifdef YOSYS_ENABLE_PLUGINS
503 for (auto &it
: loaded_plugins
)
506 loaded_plugins
.clear();
507 loaded_plugin_aliases
.clear();
511 IdString::put_reference(empty_id
.index_
);
514 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
517 size_t pos
= file
.find_last_of("/\\");
519 size_t pos
= file
.find_last_of('/');
521 if (pos
!= std::string::npos
)
522 file
= file
.substr(pos
+1);
524 pos
= func
.find_last_of(':');
525 if (pos
!= std::string::npos
)
526 func
= func
.substr(pos
+1);
528 return stringf("$auto$%s:%d:%s$%d", file
.c_str(), line
, func
.c_str(), autoidx
++);
531 RTLIL::Design
*yosys_get_design()
536 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
538 static char buffer
[100];
539 std::string str
= "\n";
540 if (recursion_counter
> 1)
541 str
+= stringf("(%d) ", recursion_counter
);
543 if (!design
->selected_active_module
.empty())
544 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
545 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
546 if (design
->selected_active_module
.empty())
548 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
549 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
552 snprintf(buffer
, 100, "%s> ", str
.c_str());
556 std::vector
<std::string
> glob_filename(const std::string
&filename_pattern
)
558 std::vector
<std::string
> results
;
561 results
.push_back(filename_pattern
);
565 int err
= glob(filename_pattern
.c_str(), 0, NULL
, &globbuf
);
568 for (size_t i
= 0; i
< globbuf
.gl_pathc
; i
++)
569 results
.push_back(globbuf
.gl_pathv
[i
]);
572 results
.push_back(filename_pattern
);
579 void rewrite_filename(std::string
&filename
)
581 if (filename
.substr(0, 1) == "\"" && filename
.substr(GetSize(filename
)-1) == "\"")
582 filename
= filename
.substr(1, GetSize(filename
)-2);
583 if (filename
.substr(0, 2) == "+/")
584 filename
= proc_share_dirname() + filename
.substr(2);
587 #ifdef YOSYS_ENABLE_TCL
588 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
590 std::vector
<std::string
> args
;
591 for (int i
= 1; i
< argc
; i
++)
592 args
.push_back(argv
[i
]);
594 if (args
.size() >= 1 && args
[0] == "-import") {
595 for (auto &it
: pass_register
) {
596 std::string tcl_command_name
= it
.first
;
597 if (tcl_command_name
== "proc")
598 tcl_command_name
= "procs";
600 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
601 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
603 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
604 Tcl_Eval(interp
, tcl_script
.c_str());
610 if (args
.size() == 1) {
611 Pass::call(yosys_get_design(), args
[0]);
615 Pass::call(yosys_get_design(), args
);
619 extern Tcl_Interp
*yosys_get_tcl_interp()
621 if (yosys_tcl_interp
== NULL
) {
622 yosys_tcl_interp
= Tcl_CreateInterp();
623 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
625 return yosys_tcl_interp
;
628 struct TclPass
: public Pass
{
629 TclPass() : Pass("tcl", "execute a TCL script file") { }
630 virtual void help() {
632 log(" tcl <filename>\n");
634 log("This command executes the tcl commands in the specified file.\n");
635 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
637 log("The tcl command 'yosys -import' can be used to import all yosys\n");
638 log("commands directly as tcl commands to the tcl shell. The yosys\n");
639 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
640 log("to avoid a name collision with the tcl builtin command 'proc'.\n");
643 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
645 log_cmd_error("Missing script file.\n");
647 extra_args(args
, 1, design
, false);
648 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
649 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
654 #if defined(__linux__) || defined(__CYGWIN__)
655 std::string
proc_self_dirname()
658 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
660 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
662 while (buflen
> 0 && path
[buflen
-1] != '/')
664 return std::string(path
, buflen
);
666 #elif defined(__APPLE__)
667 std::string
proc_self_dirname()
671 while (_NSGetExecutablePath(path
, &buflen
) != 0)
672 path
= (char *) realloc((void *) path
, buflen
);
673 while (buflen
> 0 && path
[buflen
-1] != '/')
675 return std::string(path
, buflen
);
677 #elif defined(_WIN32)
678 std::string
proc_self_dirname()
682 char longpath
[MAX_PATH
+ 1];
683 char shortpath
[MAX_PATH
+ 1];
685 WCHAR longpath
[MAX_PATH
+ 1];
686 TCHAR shortpath
[MAX_PATH
+ 1];
688 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
689 log_error("GetModuleFileName() failed.\n");
690 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
691 log_error("GetShortPathName() failed.\n");
692 while (shortpath
[i
] != 0)
694 while (i
> 0 && shortpath
[i
-1] != '/' && shortpath
[i
-1] != '\\')
697 for (i
= 0; shortpath
[i
]; i
++)
698 path
+= char(shortpath
[i
]);
701 #elif defined(EMSCRIPTEN)
702 std::string
proc_self_dirname()
707 #error Dont know how to determine process executable base path!
711 std::string
proc_share_dirname()
716 std::string
proc_share_dirname()
718 std::string proc_self_path
= proc_self_dirname();
719 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
720 std::string proc_share_path
= proc_self_path
+ "share\\";
721 if (check_file_exists(proc_share_path
, true))
722 return proc_share_path
;
723 proc_share_path
= proc_self_path
+ "..\\share\\";
724 if (check_file_exists(proc_share_path
, true))
725 return proc_share_path
;
727 std::string proc_share_path
= proc_self_path
+ "share/";
728 if (check_file_exists(proc_share_path
, true))
729 return proc_share_path
;
730 proc_share_path
= proc_self_path
+ "../share/yosys/";
731 if (check_file_exists(proc_share_path
, true))
732 return proc_share_path
;
734 proc_share_path
= YOSYS_DATDIR
"/";
735 if (check_file_exists(proc_share_path
, true))
736 return proc_share_path
;
739 log_error("proc_share_dirname: unable to determine share/ directory!\n");
743 bool fgetline(FILE *f
, std::string
&buffer
)
748 if (fgets(block
, 4096, f
) == NULL
)
751 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
752 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
753 buffer
.resize(buffer
.size()-1);
759 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
764 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
767 if (pos
< GetSize(command
) && command
[pos
] == '#')
770 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
771 label
+= command
[pos
++];
773 if (label
.back() == ':' && GetSize(label
) > 1)
775 label
= label
.substr(0, GetSize(label
)-1);
776 command
= command
.substr(pos
);
778 if (label
== run_from
)
779 from_to_active
= true;
780 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
781 from_to_active
= false;
785 void run_frontend(std::string filename
, std::string command
, std::string
*backend_command
, std::string
*from_to_label
, RTLIL::Design
*design
)
787 if (design
== nullptr)
788 design
= yosys_design
;
790 if (command
== "auto") {
791 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
793 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
794 command
= "verilog -sv";
795 else if (filename
.size() > 2 && filename
.substr(filename
.size()-4) == ".vhd")
797 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".blif")
799 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".json")
801 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
803 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
805 else if (filename
.size() > 2 && filename
.substr(filename
.size()-4) == ".tcl")
807 else if (filename
== "-")
810 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
813 if (command
== "script")
815 std::string run_from
, run_to
;
816 bool from_to_active
= true;
818 if (from_to_label
!= NULL
) {
819 size_t pos
= from_to_label
->find(':');
820 if (pos
== std::string::npos
) {
821 run_from
= *from_to_label
;
822 run_to
= *from_to_label
;
824 run_from
= from_to_label
->substr(0, pos
);
825 run_to
= from_to_label
->substr(pos
+1);
827 from_to_active
= run_from
.empty();
830 log("\n-- Executing script file `%s' --\n", filename
.c_str());
835 f
= fopen(filename
.c_str(), "r");
838 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
840 FILE *backup_script_file
= Frontend::current_script_file
;
841 Frontend::current_script_file
= f
;
845 while (fgetline(f
, command
)) {
846 while (!command
.empty() && command
[command
.size()-1] == '\\') {
847 std::string next_line
;
848 if (!fgetline(f
, next_line
))
850 command
.resize(command
.size()-1);
851 command
+= next_line
;
853 handle_label(command
, from_to_active
, run_from
, run_to
);
855 Pass::call(design
, command
);
858 if (!command
.empty()) {
859 handle_label(command
, from_to_active
, run_from
, run_to
);
861 Pass::call(design
, command
);
865 Frontend::current_script_file
= backup_script_file
;
869 Frontend::current_script_file
= backup_script_file
;
874 if (backend_command
!= NULL
&& *backend_command
== "auto")
875 *backend_command
= "";
880 if (filename
== "-") {
881 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
883 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
886 if (command
== "tcl")
887 Pass::call(design
, vector
<string
>({command
, filename
}));
889 Frontend::frontend_call(design
, NULL
, filename
, command
);
892 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
)
894 run_frontend(filename
, command
, nullptr, nullptr, design
);
897 void run_pass(std::string command
, RTLIL::Design
*design
)
899 if (design
== nullptr)
900 design
= yosys_design
;
902 log("\n-- Running command `%s' --\n", command
.c_str());
904 Pass::call(design
, command
);
907 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
909 if (design
== nullptr)
910 design
= yosys_design
;
912 if (command
== "auto") {
913 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
915 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
917 else if (filename
.size() > 4 && filename
.substr(filename
.size()-4) == ".aig")
919 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
921 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".edif")
923 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".json")
925 else if (filename
== "-")
927 else if (filename
.empty())
930 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
933 if (filename
.empty())
936 if (filename
== "-") {
937 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
939 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
942 Backend::backend_call(design
, NULL
, filename
, command
);
945 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
946 static char *readline_cmd_generator(const char *text
, int state
)
948 static std::map
<std::string
, Pass
*>::iterator it
;
952 it
= pass_register
.begin();
956 for (; it
!= pass_register
.end(); it
++) {
957 if (it
->first
.substr(0, len
) == text
)
958 return strdup((it
++)->first
.c_str());
963 static char *readline_obj_generator(const char *text
, int state
)
965 static std::vector
<char*> obj_names
;
973 RTLIL::Design
*design
= yosys_get_design();
974 int len
= strlen(text
);
976 if (design
->selected_active_module
.empty())
978 for (auto &it
: design
->modules_
)
979 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
980 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
983 if (design
->modules_
.count(design
->selected_active_module
) > 0)
985 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
987 for (auto &it
: module
->wires_
)
988 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
989 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
991 for (auto &it
: module
->memories
)
992 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
993 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
995 for (auto &it
: module
->cells_
)
996 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
997 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
999 for (auto &it
: module
->processes
)
1000 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1001 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1004 std::sort(obj_names
.begin(), obj_names
.end());
1007 if (idx
< obj_names
.size())
1008 return strdup(obj_names
[idx
++]);
1015 static char **readline_completion(const char *text
, int start
, int)
1018 return rl_completion_matches(text
, readline_cmd_generator
);
1019 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
1020 return rl_completion_matches(text
, readline_obj_generator
);
1025 void shell(RTLIL::Design
*design
)
1027 static int recursion_counter
= 0;
1029 recursion_counter
++;
1030 log_cmd_error_throw
= true;
1032 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1033 rl_readline_name
= (char*)"yosys";
1034 rl_attempted_completion_function
= readline_completion
;
1035 rl_basic_word_break_characters
= (char*)" \t\n";
1038 char *command
= NULL
;
1039 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1040 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
1043 char command_buffer
[4096];
1046 fputs(create_prompt(design
, recursion_counter
), stdout
);
1048 if ((command
= fgets(command_buffer
, 4096, stdin
)) == NULL
)
1051 if (command
[strspn(command
, " \t\r\n")] == 0)
1053 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1054 add_history(command
);
1057 char *p
= command
+ strspn(command
, " \t\r\n");
1058 if (!strncmp(p
, "exit", 4)) {
1060 p
+= strspn(p
, " \t\r\n");
1066 log_assert(design
->selection_stack
.size() == 1);
1067 Pass::call(design
, command
);
1068 } catch (log_cmd_error_exception
) {
1069 while (design
->selection_stack
.size() > 1)
1070 design
->selection_stack
.pop_back();
1074 if (command
== NULL
)
1077 recursion_counter
--;
1078 log_cmd_error_throw
= false;
1081 struct ShellPass
: public Pass
{
1082 ShellPass() : Pass("shell", "enter interactive command mode") { }
1083 virtual void help() {
1087 log("This command enters the interactive command mode. This can be useful\n");
1088 log("in a script to interrupt the script at a certain point and allow for\n");
1089 log("interactive inspection or manual synthesis of the design at this point.\n");
1091 log("The command prompt of the interactive shell indicates the current\n");
1092 log("selection (see 'help select'):\n");
1095 log(" the entire design is selected\n");
1098 log(" only part of the design is selected\n");
1100 log(" yosys [modname]>\n");
1101 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1103 log(" yosys [modname]*>\n");
1104 log(" only part of current module 'modname' is selected\n");
1106 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1107 log("do not terminate yosys but return to the command prompt.\n");
1109 log("This command is the default action if nothing else has been specified\n");
1110 log("on the command line.\n");
1112 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1115 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1116 extra_args(args
, 1, design
, false);
1121 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1122 struct HistoryPass
: public Pass
{
1123 HistoryPass() : Pass("history", "show last interactive commands") { }
1124 virtual void help() {
1128 log("This command prints all commands in the shell history buffer. This are\n");
1129 log("all commands executed in an interactive session, but not the commands\n");
1130 log("from executed scripts.\n");
1133 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1134 extra_args(args
, 1, design
, false);
1135 #ifdef YOSYS_ENABLE_READLINE
1136 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
1137 log("%s\n", (*list
)->line
);
1139 for (int i
= where_history(); history_get(i
); i
++)
1140 log("%s\n", history_get(i
)->line
);
1146 struct ScriptCmdPass
: public Pass
{
1147 ScriptCmdPass() : Pass("script", "execute commands from script file") { }
1148 virtual void help() {
1150 log(" script <filename> [<from_label>:<to_label>]\n");
1152 log("This command executes the yosys commands in the specified file.\n");
1154 log("The 2nd argument can be used to only execute the section of the\n");
1155 log("file between the specified labels. An empty from label is synonymous\n");
1156 log("for the beginning of the file and an empty to label is synonymous\n");
1157 log("for the end of the file.\n");
1159 log("If only one label is specified (without ':') then only the block\n");
1160 log("marked with that label (until the next label) is executed.\n");
1163 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
1164 if (args
.size() < 2)
1165 log_cmd_error("Missing script file.\n");
1166 else if (args
.size() == 2)
1167 run_frontend(args
[1], "script", design
);
1168 else if (args
.size() == 3)
1169 run_frontend(args
[1], "script", NULL
, &args
[2], design
);
1171 extra_args(args
, 2, design
, false);