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/wait.h>
49 # include <sys/stat.h>
52 #if !defined(_WIN32) && defined(YOSYS_ENABLE_GLOB)
57 # include <sys/sysctl.h>
67 RTLIL::Design
*yosys_design
= NULL
;
68 CellTypes yosys_celltypes
;
70 #ifdef YOSYS_ENABLE_TCL
71 Tcl_Interp
*yosys_tcl_interp
= NULL
;
74 std::set
<std::string
> yosys_input_files
, yosys_output_files
;
76 bool memhasher_active
= false;
77 uint32_t memhasher_rng
= 123456;
78 std::vector
<void*> memhasher_store
;
82 #if defined(__linux__) || defined(__FreeBSD__)
83 memhasher_rng
+= time(NULL
) << 16 ^ getpid();
85 memhasher_store
.resize(0x10000);
86 memhasher_active
= true;
91 for (auto p
: memhasher_store
)
93 memhasher_store
.clear();
94 memhasher_active
= false;
99 memhasher_rng
^= memhasher_rng
<< 13;
100 memhasher_rng
^= memhasher_rng
>> 17;
101 memhasher_rng
^= memhasher_rng
<< 5;
103 int size
, index
= (memhasher_rng
>> 4) & 0xffff;
104 switch (memhasher_rng
& 7) {
105 case 0: size
= 16; break;
106 case 1: size
= 256; break;
107 case 2: size
= 1024; break;
108 case 3: size
= 4096; break;
111 if (index
< 16) size
*= 16;
112 memhasher_store
[index
] = realloc(memhasher_store
[index
], size
);
118 log(" /----------------------------------------------------------------------------\\\n");
120 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
122 log(" | Copyright (C) 2012 - 2018 Clifford Wolf <clifford@clifford.at> |\n");
124 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
125 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
126 log(" | copyright notice and this permission notice appear in all copies. |\n");
128 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
129 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
130 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
131 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
132 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
133 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
134 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
136 log(" \\----------------------------------------------------------------------------/\n");
138 log(" %s\n", yosys_version_str
);
147 for (int i
= 0; i
< 32; i
++)
148 if (((x
-1) >> i
) == 0)
154 std::string
stringf(const char *fmt
, ...)
160 string
= vstringf(fmt
, ap
);
166 std::string
vstringf(const char *fmt
, va_list ap
)
171 #if defined(_WIN32 )|| defined(__CYGWIN__)
176 str
= (char*)realloc(str
, sz
);
177 rc
= vsnprintf(str
, sz
, fmt
, apc
);
179 if (rc
>= 0 && rc
< sz
)
184 if (vasprintf(&str
, fmt
, ap
) < 0)
196 int readsome(std::istream
&f
, char *s
, int n
)
198 int rc
= int(f
.readsome(s
, n
));
200 // f.readsome() sometimes returns 0 on a non-empty stream..
212 std::string
next_token(std::string
&text
, const char *sep
, bool long_strings
)
214 size_t pos_begin
= text
.find_first_not_of(sep
);
216 if (pos_begin
== std::string::npos
)
217 pos_begin
= text
.size();
219 if (long_strings
&& pos_begin
!= text
.size() && text
[pos_begin
] == '"') {
220 string sep_string
= sep
;
221 for (size_t i
= pos_begin
+1; i
< text
.size(); i
++) {
222 if (text
[i
] == '"' && (i
+1 == text
.size() || sep_string
.find(text
[i
+1]) != std::string::npos
)) {
223 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
224 text
= text
.substr(i
+1);
227 if (i
+1 < text
.size() && text
[i
] == '"' && text
[i
+1] == ';' && (i
+2 == text
.size() || sep_string
.find(text
[i
+2]) != std::string::npos
)) {
228 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
229 text
= text
.substr(i
+2);
235 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
237 if (pos_end
== std::string::npos
)
238 pos_end
= text
.size();
240 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
241 text
= text
.substr(pos_end
);
245 std::vector
<std::string
> split_tokens(const std::string
&text
, const char *sep
)
247 std::vector
<std::string
> tokens
;
248 std::string current_token
;
249 for (char c
: text
) {
250 if (strchr(sep
, c
)) {
251 if (!current_token
.empty()) {
252 tokens
.push_back(current_token
);
253 current_token
.clear();
258 if (!current_token
.empty()) {
259 tokens
.push_back(current_token
);
260 current_token
.clear();
265 // this is very similar to fnmatch(). the exact rules used by this
268 // ? matches any character except
269 // * matches any sequence of characters
270 // [...] matches any of the characters in the list
271 // [!..] matches any of the characters not in the list
273 // a backslash may be used to escape the next characters in the
274 // pattern. each special character can also simply match itself.
276 bool patmatch(const char *pattern
, const char *string
)
281 if (*pattern
== '\\') {
282 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
286 if (*pattern
== '?') {
289 return patmatch(pattern
+1, string
+1);
292 if (*pattern
== '*') {
294 if (patmatch(pattern
+1, string
++))
297 return pattern
[1] == 0;
300 if (*pattern
== '[') {
301 bool found_match
= false;
302 bool inverted_list
= pattern
[1] == '!';
303 const char *p
= pattern
+ (inverted_list
? 1 : 0);
307 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
321 if (*pattern
== *string
)
322 return patmatch(pattern
+1, string
+1);
327 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
330 return system(command
.c_str());
332 FILE *f
= popen(command
.c_str(), "r");
338 while (fgets(logbuf
, 128, f
) != NULL
) {
340 if (!line
.empty() && line
.back() == '\n')
341 process_line(line
), line
.clear();
352 return WEXITSTATUS(ret
);
356 std::string
make_temp_file(std::string template_str
)
359 if (template_str
.rfind("/tmp/", 0) == 0) {
361 char longpath
[MAX_PATH
+ 1];
362 char shortpath
[MAX_PATH
+ 1];
364 WCHAR longpath
[MAX_PATH
+ 1];
365 TCHAR shortpath
[MAX_PATH
+ 1];
367 if (!GetTempPath(MAX_PATH
+1, longpath
))
368 log_error("GetTempPath() failed.\n");
369 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+ 1))
370 log_error("GetShortPathName() failed.\n");
372 for (int i
= 0; shortpath
[i
]; i
++)
373 path
+= char(shortpath
[i
]);
374 template_str
= stringf("%s\\%s", path
.c_str(), template_str
.c_str() + 5);
377 size_t pos
= template_str
.rfind("XXXXXX");
378 log_assert(pos
!= std::string::npos
);
381 for (int i
= 0; i
< 6; i
++) {
382 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
383 static uint32_t x
= 314159265 ^ uint32_t(time(NULL
));
384 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
385 template_str
[pos
+i
] = y
[x
% y
.size()];
387 if (_access(template_str
.c_str(), 0) != 0)
391 size_t pos
= template_str
.rfind("XXXXXX");
392 log_assert(pos
!= std::string::npos
);
394 int suffixlen
= GetSize(template_str
) - pos
- 6;
396 char *p
= strdup(template_str
.c_str());
397 close(mkstemps(p
, suffixlen
));
405 std::string
make_temp_dir(std::string template_str
)
408 template_str
= make_temp_file(template_str
);
409 mkdir(template_str
.c_str());
413 size_t pos
= template_str
.rfind("XXXXXX");
414 log_assert(pos
!= std::string::npos
);
416 int suffixlen
= GetSize(template_str
) - pos
- 6;
417 log_assert(suffixlen
== 0);
420 char *p
= strdup(template_str
.c_str());
422 log_assert(p
!= NULL
);
431 bool check_file_exists(std::string filename
, bool)
433 return _access(filename
.c_str(), 0) == 0;
436 bool check_file_exists(std::string filename
, bool is_exec
)
438 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
442 bool is_absolute_path(std::string filename
)
445 return filename
[0] == '/' || filename
[0] == '\\' || (filename
[0] != 0 && filename
[1] == ':');
447 return filename
[0] == '/';
451 void remove_directory(std::string dirname
)
454 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
457 struct dirent
**namelist
;
458 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
460 for (int i
= 0; i
< n
; i
++) {
461 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
462 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
463 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
464 remove(buffer
.c_str());
466 remove_directory(buffer
);
471 rmdir(dirname
.c_str());
475 int GetSize(RTLIL::Wire
*wire
)
482 // if there are already IdString objects then we have a global initialization order bug
484 log_assert(empty_id
.index_
== 0);
485 IdString::get_reference(empty_id
.index_
);
487 Pass::init_register();
488 yosys_design
= new RTLIL::Design
;
489 yosys_celltypes
.setup();
493 void yosys_shutdown()
500 for (auto f
: log_files
)
506 Pass::done_register();
507 yosys_celltypes
.clear();
509 #ifdef YOSYS_ENABLE_TCL
510 if (yosys_tcl_interp
!= NULL
) {
511 Tcl_DeleteInterp(yosys_tcl_interp
);
513 yosys_tcl_interp
= NULL
;
517 #ifdef YOSYS_ENABLE_PLUGINS
518 for (auto &it
: loaded_plugins
)
521 loaded_plugins
.clear();
522 loaded_plugin_aliases
.clear();
526 IdString::put_reference(empty_id
.index_
);
529 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
532 size_t pos
= file
.find_last_of("/\\");
534 size_t pos
= file
.find_last_of('/');
536 if (pos
!= std::string::npos
)
537 file
= file
.substr(pos
+1);
539 pos
= func
.find_last_of(':');
540 if (pos
!= std::string::npos
)
541 func
= func
.substr(pos
+1);
543 return stringf("$auto$%s:%d:%s$%d", file
.c_str(), line
, func
.c_str(), autoidx
++);
546 RTLIL::Design
*yosys_get_design()
551 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
553 static char buffer
[100];
554 std::string str
= "\n";
555 if (recursion_counter
> 1)
556 str
+= stringf("(%d) ", recursion_counter
);
558 if (!design
->selected_active_module
.empty())
559 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
560 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
561 if (design
->selected_active_module
.empty())
563 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
564 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
567 snprintf(buffer
, 100, "%s> ", str
.c_str());
571 std::vector
<std::string
> glob_filename(const std::string
&filename_pattern
)
573 std::vector
<std::string
> results
;
575 #if defined(_WIN32) || !defined(YOSYS_ENABLE_GLOB)
576 results
.push_back(filename_pattern
);
580 int err
= glob(filename_pattern
.c_str(), 0, NULL
, &globbuf
);
583 for (size_t i
= 0; i
< globbuf
.gl_pathc
; i
++)
584 results
.push_back(globbuf
.gl_pathv
[i
]);
587 results
.push_back(filename_pattern
);
594 void rewrite_filename(std::string
&filename
)
596 if (filename
.substr(0, 1) == "\"" && filename
.substr(GetSize(filename
)-1) == "\"")
597 filename
= filename
.substr(1, GetSize(filename
)-2);
598 if (filename
.substr(0, 2) == "+/")
599 filename
= proc_share_dirname() + filename
.substr(2);
602 #ifdef YOSYS_ENABLE_TCL
603 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
605 std::vector
<std::string
> args
;
606 for (int i
= 1; i
< argc
; i
++)
607 args
.push_back(argv
[i
]);
609 if (args
.size() >= 1 && args
[0] == "-import") {
610 for (auto &it
: pass_register
) {
611 std::string tcl_command_name
= it
.first
;
612 if (tcl_command_name
== "proc")
613 tcl_command_name
= "procs";
614 else if (tcl_command_name
== "rename")
615 tcl_command_name
= "renames";
617 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
618 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
620 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
621 Tcl_Eval(interp
, tcl_script
.c_str());
627 if (args
.size() == 1) {
628 Pass::call(yosys_get_design(), args
[0]);
632 Pass::call(yosys_get_design(), args
);
636 extern Tcl_Interp
*yosys_get_tcl_interp()
638 if (yosys_tcl_interp
== NULL
) {
639 yosys_tcl_interp
= Tcl_CreateInterp();
640 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
642 return yosys_tcl_interp
;
645 struct TclPass
: public Pass
{
646 TclPass() : Pass("tcl", "execute a TCL script file") { }
647 void help() YS_OVERRIDE
{
648 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
650 log(" tcl <filename> [args]\n");
652 log("This command executes the tcl commands in the specified file.\n");
653 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
655 log("The tcl command 'yosys -import' can be used to import all yosys\n");
656 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
657 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
658 log("in order to avoid a name collision with the built in commands.\n");
660 log("If any arguments are specified, these arguments are provided to the script via\n");
661 log("the standard $argc and $argv variables.\n");
664 void execute(std::vector
<std::string
> args
, RTLIL::Design
*) YS_OVERRIDE
{
666 log_cmd_error("Missing script file.\n");
668 std::vector
<Tcl_Obj
*> script_args
;
669 for (auto it
= args
.begin() + 2; it
!= args
.end(); ++it
)
670 script_args
.push_back(Tcl_NewStringObj((*it
).c_str(), (*it
).size()));
672 Tcl_Interp
*interp
= yosys_get_tcl_interp();
673 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argc", 4), NULL
, Tcl_NewIntObj(script_args
.size()), 0);
674 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv", 4), NULL
, Tcl_NewListObj(script_args
.size(), script_args
.data()), 0);
675 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv0", 5), NULL
, Tcl_NewStringObj(args
[1].c_str(), args
[1].size()), 0);
676 if (Tcl_EvalFile(interp
, args
[1].c_str()) != TCL_OK
)
677 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp
));
682 #if defined(__linux__) || defined(__CYGWIN__)
683 std::string
proc_self_dirname()
686 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
688 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
690 while (buflen
> 0 && path
[buflen
-1] != '/')
692 return std::string(path
, buflen
);
694 #elif defined(__FreeBSD__)
695 std::string
proc_self_dirname()
697 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
701 if (sysctl(mib
, 4, NULL
, &buflen
, NULL
, 0) != 0)
702 log_error("sysctl failed: %s\n", strerror(errno
));
703 buffer
= (char*)malloc(buflen
);
705 log_error("malloc failed: %s\n", strerror(errno
));
706 if (sysctl(mib
, 4, buffer
, &buflen
, NULL
, 0) != 0)
707 log_error("sysctl failed: %s\n", strerror(errno
));
708 while (buflen
> 0 && buffer
[buflen
-1] != '/')
710 path
.assign(buffer
, buflen
);
714 #elif defined(__APPLE__)
715 std::string
proc_self_dirname()
719 while (_NSGetExecutablePath(path
, &buflen
) != 0)
720 path
= (char *) realloc((void *) path
, buflen
);
721 while (buflen
> 0 && path
[buflen
-1] != '/')
723 return std::string(path
, buflen
);
725 #elif defined(_WIN32)
726 std::string
proc_self_dirname()
730 char longpath
[MAX_PATH
+ 1];
731 char shortpath
[MAX_PATH
+ 1];
733 WCHAR longpath
[MAX_PATH
+ 1];
734 TCHAR shortpath
[MAX_PATH
+ 1];
736 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
737 log_error("GetModuleFileName() failed.\n");
738 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
739 log_error("GetShortPathName() failed.\n");
740 while (shortpath
[i
] != 0)
742 while (i
> 0 && shortpath
[i
-1] != '/' && shortpath
[i
-1] != '\\')
745 for (i
= 0; shortpath
[i
]; i
++)
746 path
+= char(shortpath
[i
]);
749 #elif defined(EMSCRIPTEN)
750 std::string
proc_self_dirname()
755 #error "Don't know how to determine process executable base path!"
759 std::string
proc_share_dirname()
764 std::string
proc_share_dirname()
766 std::string proc_self_path
= proc_self_dirname();
767 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
768 std::string proc_share_path
= proc_self_path
+ "share\\";
769 if (check_file_exists(proc_share_path
, true))
770 return proc_share_path
;
771 proc_share_path
= proc_self_path
+ "..\\share\\";
772 if (check_file_exists(proc_share_path
, true))
773 return proc_share_path
;
775 std::string proc_share_path
= proc_self_path
+ "share/";
776 if (check_file_exists(proc_share_path
, true))
777 return proc_share_path
;
778 proc_share_path
= proc_self_path
+ "../share/yosys/";
779 if (check_file_exists(proc_share_path
, true))
780 return proc_share_path
;
782 proc_share_path
= YOSYS_DATDIR
"/";
783 if (check_file_exists(proc_share_path
, true))
784 return proc_share_path
;
787 log_error("proc_share_dirname: unable to determine share/ directory!\n");
791 bool fgetline(FILE *f
, std::string
&buffer
)
796 if (fgets(block
, 4096, f
) == NULL
)
799 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
800 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
801 buffer
.resize(buffer
.size()-1);
807 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
812 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
815 if (pos
< GetSize(command
) && command
[pos
] == '#')
818 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
819 label
+= command
[pos
++];
821 if (GetSize(label
) > 1 && label
.back() == ':')
823 label
= label
.substr(0, GetSize(label
)-1);
824 command
= command
.substr(pos
);
826 if (label
== run_from
)
827 from_to_active
= true;
828 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
829 from_to_active
= false;
833 void run_frontend(std::string filename
, std::string command
, std::string
*backend_command
, std::string
*from_to_label
, RTLIL::Design
*design
)
835 if (design
== nullptr)
836 design
= yosys_design
;
838 if (command
== "auto") {
839 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
841 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
842 command
= "verilog -sv";
843 else if (filename
.size() > 3 && filename
.substr(filename
.size()-4) == ".vhd")
845 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".blif")
847 else if (filename
.size() > 5 && filename
.substr(filename
.size()-6) == ".eblif")
849 else if (filename
.size() > 4 && filename
.substr(filename
.size()-5) == ".json")
851 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
853 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
855 else if (filename
.size() > 3 && filename
.substr(filename
.size()-4) == ".tcl")
857 else if (filename
== "-")
860 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
863 if (command
== "script")
865 std::string run_from
, run_to
;
866 bool from_to_active
= true;
868 if (from_to_label
!= NULL
) {
869 size_t pos
= from_to_label
->find(':');
870 if (pos
== std::string::npos
) {
871 run_from
= *from_to_label
;
872 run_to
= *from_to_label
;
874 run_from
= from_to_label
->substr(0, pos
);
875 run_to
= from_to_label
->substr(pos
+1);
877 from_to_active
= run_from
.empty();
880 log("\n-- Executing script file `%s' --\n", filename
.c_str());
884 if (filename
!= "-") {
885 f
= fopen(filename
.c_str(), "r");
886 yosys_input_files
.insert(filename
);
890 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
892 FILE *backup_script_file
= Frontend::current_script_file
;
893 Frontend::current_script_file
= f
;
897 while (fgetline(f
, command
)) {
898 while (!command
.empty() && command
[command
.size()-1] == '\\') {
899 std::string next_line
;
900 if (!fgetline(f
, next_line
))
902 command
.resize(command
.size()-1);
903 command
+= next_line
;
905 handle_label(command
, from_to_active
, run_from
, run_to
);
907 Pass::call(design
, command
);
910 if (!command
.empty()) {
911 handle_label(command
, from_to_active
, run_from
, run_to
);
913 Pass::call(design
, command
);
917 Frontend::current_script_file
= backup_script_file
;
921 Frontend::current_script_file
= backup_script_file
;
926 if (backend_command
!= NULL
&& *backend_command
== "auto")
927 *backend_command
= "";
932 if (filename
== "-") {
933 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
935 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
938 if (command
== "tcl")
939 Pass::call(design
, vector
<string
>({command
, filename
}));
941 Frontend::frontend_call(design
, NULL
, filename
, command
);
944 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
)
946 run_frontend(filename
, command
, nullptr, nullptr, design
);
949 void run_pass(std::string command
, RTLIL::Design
*design
)
951 if (design
== nullptr)
952 design
= yosys_design
;
954 log("\n-- Running command `%s' --\n", command
.c_str());
956 Pass::call(design
, command
);
959 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
961 if (design
== nullptr)
962 design
= yosys_design
;
964 if (command
== "auto") {
965 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
967 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
969 else if (filename
.size() > 4 && filename
.substr(filename
.size()-4) == ".aig")
971 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
973 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".edif")
975 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".json")
977 else if (filename
== "-")
979 else if (filename
.empty())
982 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
985 if (filename
.empty())
988 if (filename
== "-") {
989 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
991 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
994 Backend::backend_call(design
, NULL
, filename
, command
);
997 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
998 static char *readline_cmd_generator(const char *text
, int state
)
1000 static std::map
<std::string
, Pass
*>::iterator it
;
1004 it
= pass_register
.begin();
1008 for (; it
!= pass_register
.end(); it
++) {
1009 if (it
->first
.substr(0, len
) == text
)
1010 return strdup((it
++)->first
.c_str());
1015 static char *readline_obj_generator(const char *text
, int state
)
1017 static std::vector
<char*> obj_names
;
1025 RTLIL::Design
*design
= yosys_get_design();
1026 int len
= strlen(text
);
1028 if (design
->selected_active_module
.empty())
1030 for (auto &it
: design
->modules_
)
1031 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1032 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1035 if (design
->modules_
.count(design
->selected_active_module
) > 0)
1037 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
1039 for (auto &it
: module
->wires_
)
1040 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1041 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1043 for (auto &it
: module
->memories
)
1044 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1045 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1047 for (auto &it
: module
->cells_
)
1048 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1049 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1051 for (auto &it
: module
->processes
)
1052 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
1053 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1056 std::sort(obj_names
.begin(), obj_names
.end());
1059 if (idx
< obj_names
.size())
1060 return strdup(obj_names
[idx
++]);
1067 static char **readline_completion(const char *text
, int start
, int)
1070 return rl_completion_matches(text
, readline_cmd_generator
);
1071 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
1072 return rl_completion_matches(text
, readline_obj_generator
);
1077 void shell(RTLIL::Design
*design
)
1079 static int recursion_counter
= 0;
1081 recursion_counter
++;
1082 log_cmd_error_throw
= true;
1084 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1085 rl_readline_name
= (char*)"yosys";
1086 rl_attempted_completion_function
= readline_completion
;
1087 rl_basic_word_break_characters
= (char*)" \t\n";
1090 char *command
= NULL
;
1091 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1092 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
1095 char command_buffer
[4096];
1098 fputs(create_prompt(design
, recursion_counter
), stdout
);
1100 if ((command
= fgets(command_buffer
, 4096, stdin
)) == NULL
)
1103 if (command
[strspn(command
, " \t\r\n")] == 0)
1105 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1106 add_history(command
);
1109 char *p
= command
+ strspn(command
, " \t\r\n");
1110 if (!strncmp(p
, "exit", 4)) {
1112 p
+= strspn(p
, " \t\r\n");
1118 log_assert(design
->selection_stack
.size() == 1);
1119 Pass::call(design
, command
);
1120 } catch (log_cmd_error_exception
) {
1121 while (design
->selection_stack
.size() > 1)
1122 design
->selection_stack
.pop_back();
1126 if (command
== NULL
)
1129 recursion_counter
--;
1130 log_cmd_error_throw
= false;
1133 struct ShellPass
: public Pass
{
1134 ShellPass() : Pass("shell", "enter interactive command mode") { }
1135 void help() YS_OVERRIDE
{
1139 log("This command enters the interactive command mode. This can be useful\n");
1140 log("in a script to interrupt the script at a certain point and allow for\n");
1141 log("interactive inspection or manual synthesis of the design at this point.\n");
1143 log("The command prompt of the interactive shell indicates the current\n");
1144 log("selection (see 'help select'):\n");
1147 log(" the entire design is selected\n");
1150 log(" only part of the design is selected\n");
1152 log(" yosys [modname]>\n");
1153 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1155 log(" yosys [modname]*>\n");
1156 log(" only part of current module 'modname' is selected\n");
1158 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1159 log("do not terminate yosys but return to the command prompt.\n");
1161 log("This command is the default action if nothing else has been specified\n");
1162 log("on the command line.\n");
1164 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1167 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
{
1168 extra_args(args
, 1, design
, false);
1173 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1174 struct HistoryPass
: public Pass
{
1175 HistoryPass() : Pass("history", "show last interactive commands") { }
1176 void help() YS_OVERRIDE
{
1180 log("This command prints all commands in the shell history buffer. This are\n");
1181 log("all commands executed in an interactive session, but not the commands\n");
1182 log("from executed scripts.\n");
1185 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
{
1186 extra_args(args
, 1, design
, false);
1187 #ifdef YOSYS_ENABLE_READLINE
1188 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
1189 log("%s\n", (*list
)->line
);
1191 for (int i
= where_history(); history_get(i
); i
++)
1192 log("%s\n", history_get(i
)->line
);
1198 struct ScriptCmdPass
: public Pass
{
1199 ScriptCmdPass() : Pass("script", "execute commands from script file") { }
1200 void help() YS_OVERRIDE
{
1202 log(" script <filename> [<from_label>:<to_label>]\n");
1204 log("This command executes the yosys commands in the specified file.\n");
1206 log("The 2nd argument can be used to only execute the section of the\n");
1207 log("file between the specified labels. An empty from label is synonymous\n");
1208 log("for the beginning of the file and an empty to label is synonymous\n");
1209 log("for the end of the file.\n");
1211 log("If only one label is specified (without ':') then only the block\n");
1212 log("marked with that label (until the next label) is executed.\n");
1215 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
{
1216 if (args
.size() < 2)
1217 log_cmd_error("Missing script file.\n");
1218 else if (args
.size() == 2)
1219 run_frontend(args
[1], "script", design
);
1220 else if (args
.size() == 3)
1221 run_frontend(args
[1], "script", NULL
, &args
[2], design
);
1223 extra_args(args
, 2, design
, false);