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"
22 #ifdef YOSYS_ENABLE_READLINE
23 # include <readline/readline.h>
24 # include <readline/history.h>
27 #ifdef YOSYS_ENABLE_PLUGINS
42 RTLIL::Design
*yosys_design
= NULL
;
44 #ifdef YOSYS_ENABLE_TCL
45 Tcl_Interp
*yosys_tcl_interp
= NULL
;
48 std::string
stringf(const char *fmt
, ...)
54 string
= vstringf(fmt
, ap
);
60 std::string
vstringf(const char *fmt
, va_list ap
)
70 str
= (char*)realloc(str
, sz
);
71 rc
= vsnprintf(str
, sz
, fmt
, apc
);
73 if (rc
>= 0 && rc
< sz
)
78 if (vasprintf(&str
, fmt
, ap
) < 0)
90 std::string
next_token(std::string
&text
, const char *sep
)
92 size_t pos_begin
= text
.find_first_not_of(sep
);
94 if (pos_begin
== std::string::npos
)
95 pos_begin
= text
.size();
97 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
99 if (pos_end
== std::string::npos
)
100 pos_end
= text
.size();
102 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
103 text
= text
.substr(pos_end
);
107 // this is very similar to fnmatch(). the exact rules used by this
110 // ? matches any character except
111 // * matches any sequence of characters
112 // [...] matches any of the characters in the list
113 // [!..] matches any of the characters not in the list
115 // a backslash may be used to escape the next characters in the
116 // pattern. each special character can also simply match itself.
118 bool patmatch(const char *pattern
, const char *string
)
123 if (*pattern
== '\\') {
124 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
128 if (*pattern
== '?') {
131 return patmatch(pattern
+1, string
+1);
134 if (*pattern
== '*') {
136 if (patmatch(pattern
+1, string
++))
139 return pattern
[1] == 0;
142 if (*pattern
== '[') {
143 bool found_match
= false;
144 bool inverted_list
= pattern
[1] == '!';
145 const char *p
= pattern
+ (inverted_list
? 1 : 0);
149 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
163 if (*pattern
== *string
)
164 return patmatch(pattern
+1, string
+1);
169 int readsome(std::istream
&f
, char *s
, int n
)
171 int rc
= f
.readsome(s
, n
);
173 // win32 sometimes returns 0 on a non-empty stream..
185 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
188 return system(command
.c_str());
190 FILE *f
= popen(command
.c_str(), "r");
196 while (fgets(logbuf
, 128, f
) != NULL
) {
198 if (!line
.empty() && line
.back() == '\n')
199 process_line(line
), line
.clear();
207 return WEXITSTATUS(ret
);
210 int GetSize(RTLIL::Wire
*wire
)
217 Pass::init_register();
218 yosys_design
= new RTLIL::Design
;
222 void yosys_shutdown()
229 for (auto f
: log_files
)
235 Pass::done_register();
237 #ifdef YOSYS_ENABLE_TCL
238 if (yosys_tcl_interp
!= NULL
) {
239 Tcl_DeleteInterp(yosys_tcl_interp
);
241 yosys_tcl_interp
= NULL
;
245 #ifdef YOSYS_ENABLE_PLUGINS
246 for (auto &it
: loaded_plugins
)
250 loaded_plugins
.clear();
251 loaded_plugin_aliases
.clear();
254 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
256 std::string str
= "$auto$";
257 size_t pos
= file
.find_last_of('/');
258 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
259 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
263 RTLIL::Design
*yosys_get_design()
268 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
270 static char buffer
[100];
271 std::string str
= "\n";
272 if (recursion_counter
> 1)
273 str
+= stringf("(%d) ", recursion_counter
);
275 if (!design
->selected_active_module
.empty())
276 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
277 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
278 if (design
->selected_active_module
.empty())
280 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
281 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
284 snprintf(buffer
, 100, "%s> ", str
.c_str());
288 #ifdef YOSYS_ENABLE_TCL
289 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
291 std::vector
<std::string
> args
;
292 for (int i
= 1; i
< argc
; i
++)
293 args
.push_back(argv
[i
]);
295 if (args
.size() >= 1 && args
[0] == "-import") {
296 for (auto &it
: pass_register
) {
297 std::string tcl_command_name
= it
.first
;
298 if (tcl_command_name
== "proc")
299 tcl_command_name
= "procs";
301 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
302 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
304 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
305 Tcl_Eval(interp
, tcl_script
.c_str());
311 if (args
.size() == 1) {
312 Pass::call(yosys_get_design(), args
[0]);
316 Pass::call(yosys_get_design(), args
);
320 extern Tcl_Interp
*yosys_get_tcl_interp()
322 if (yosys_tcl_interp
== NULL
) {
323 yosys_tcl_interp
= Tcl_CreateInterp();
324 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
326 return yosys_tcl_interp
;
329 struct TclPass
: public Pass
{
330 TclPass() : Pass("tcl", "execute a TCL script file") { }
331 virtual void help() {
333 log(" tcl <filename>\n");
335 log("This command executes the tcl commands in the specified file.\n");
336 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
338 log("The tcl command 'yosys -import' can be used to import all yosys\n");
339 log("commands directly as tcl commands to the tcl shell. The yosys\n");
340 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
341 log("to avoid a name collision with the tcl builting command 'proc'.\n");
344 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
346 log_cmd_error("Missing script file.\n");
348 extra_args(args
, 1, design
, false);
349 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
350 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
355 #if defined(__linux__)
356 std::string
proc_self_dirname()
359 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
361 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
363 while (buflen
> 0 && path
[buflen
-1] != '/')
365 return std::string(path
, buflen
);
367 #elif defined(__APPLE__)
368 #include <mach-o/dyld.h>
369 std::string
proc_self_dirname()
373 while (_NSGetExecutablePath(path
, &buflen
) != 0)
374 path
= (char *) realloc((void *) path
, buflen
);
375 while (buflen
> 0 && path
[buflen
-1] != '/')
377 return std::string(path
, buflen
);
379 #elif defined(_WIN32)
380 std::string
proc_self_dirname()
382 char path
[MAX_PATH
+1];
383 if (!GetModuleFileName(0, path
, MAX_PATH
+1))
384 log_error("GetModuleFileName() failed.\n");
385 for (int i
= strlen(path
)-1; i
>= 0 && path
[i
] != '/' && path
[i
] != '\\' ; i
--)
387 return std::string(path
);
389 #elif defined(EMSCRIPTEN)
390 std::string
proc_self_dirname()
395 #error Dont know how to determine process executable base path!
398 std::string
proc_share_dirname()
400 std::string proc_self_path
= proc_self_dirname();
401 std::string proc_share_path
= proc_self_path
+ "share/";
402 if (access(proc_share_path
.c_str(), X_OK
) == 0)
403 return proc_share_path
;
404 proc_share_path
= proc_self_path
+ "../share/yosys/";
405 if (access(proc_share_path
.c_str(), X_OK
) == 0)
406 return proc_share_path
;
407 log_error("proc_share_dirname: unable to determine share/ directory!\n");
410 bool fgetline(FILE *f
, std::string
&buffer
)
415 if (fgets(block
, 4096, f
) == NULL
)
418 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
419 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
420 buffer
.resize(buffer
.size()-1);
426 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
431 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
434 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
435 label
+= command
[pos
++];
437 if (label
.back() == ':' && GetSize(label
) > 1)
439 label
= label
.substr(0, GetSize(label
)-1);
440 command
= command
.substr(pos
);
442 if (label
== run_from
)
443 from_to_active
= true;
444 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
445 from_to_active
= false;
449 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
451 if (command
== "auto") {
452 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
454 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
455 command
= "verilog -sv";
456 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
458 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
460 else if (filename
== "-")
463 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
466 if (command
== "script")
468 std::string run_from
, run_to
;
469 bool from_to_active
= true;
471 if (from_to_label
!= NULL
) {
472 size_t pos
= from_to_label
->find(':');
473 if (pos
== std::string::npos
) {
474 run_from
= *from_to_label
;
475 run_to
= *from_to_label
;
477 run_from
= from_to_label
->substr(0, pos
);
478 run_to
= from_to_label
->substr(pos
+1);
480 from_to_active
= run_from
.empty();
483 log("\n-- Executing script file `%s' --\n", filename
.c_str());
488 f
= fopen(filename
.c_str(), "r");
491 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
493 FILE *backup_script_file
= Frontend::current_script_file
;
494 Frontend::current_script_file
= f
;
498 while (fgetline(f
, command
)) {
499 while (!command
.empty() && command
[command
.size()-1] == '\\') {
500 std::string next_line
;
501 if (!fgetline(f
, next_line
))
503 command
.resize(command
.size()-1);
504 command
+= next_line
;
506 handle_label(command
, from_to_active
, run_from
, run_to
);
508 Pass::call(design
, command
);
511 if (!command
.empty()) {
512 handle_label(command
, from_to_active
, run_from
, run_to
);
514 Pass::call(design
, command
);
517 catch (log_cmd_error_expection
) {
518 Frontend::current_script_file
= backup_script_file
;
519 throw log_cmd_error_expection();
522 Frontend::current_script_file
= backup_script_file
;
527 if (backend_command
!= NULL
&& *backend_command
== "auto")
528 *backend_command
= "";
533 if (filename
== "-") {
534 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
536 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
539 Frontend::frontend_call(design
, NULL
, filename
, command
);
542 void run_pass(std::string command
, RTLIL::Design
*design
)
544 log("\n-- Running pass `%s' --\n", command
.c_str());
546 Pass::call(design
, command
);
549 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
551 if (command
== "auto") {
552 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
554 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
556 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
558 else if (filename
== "-")
560 else if (filename
.empty())
563 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
566 if (filename
.empty())
569 if (filename
== "-") {
570 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
572 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
575 Backend::backend_call(design
, NULL
, filename
, command
);
578 #ifdef YOSYS_ENABLE_READLINE
579 static char *readline_cmd_generator(const char *text
, int state
)
581 static std::map
<std::string
, Pass
*>::iterator it
;
585 it
= pass_register
.begin();
589 for (; it
!= pass_register
.end(); it
++) {
590 if (it
->first
.substr(0, len
) == text
)
591 return strdup((it
++)->first
.c_str());
596 static char *readline_obj_generator(const char *text
, int state
)
598 static std::vector
<char*> obj_names
;
606 RTLIL::Design
*design
= yosys_get_design();
607 int len
= strlen(text
);
609 if (design
->selected_active_module
.empty())
611 for (auto &it
: design
->modules_
)
612 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
613 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
616 if (design
->modules_
.count(design
->selected_active_module
) > 0)
618 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
620 for (auto &it
: module
->wires_
)
621 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
622 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
624 for (auto &it
: module
->memories
)
625 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
626 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
628 for (auto &it
: module
->cells_
)
629 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
630 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
632 for (auto &it
: module
->processes
)
633 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
634 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
637 std::sort(obj_names
.begin(), obj_names
.end());
640 if (idx
< obj_names
.size())
641 return strdup(obj_names
[idx
++]);
648 static char **readline_completion(const char *text
, int start
, int)
651 return rl_completion_matches(text
, readline_cmd_generator
);
652 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
653 return rl_completion_matches(text
, readline_obj_generator
);
658 void shell(RTLIL::Design
*design
)
660 static int recursion_counter
= 0;
663 log_cmd_error_throw
= true;
665 #ifdef YOSYS_ENABLE_READLINE
666 rl_readline_name
= "yosys";
667 rl_attempted_completion_function
= readline_completion
;
668 rl_basic_word_break_characters
= " \t\n";
671 char *command
= NULL
;
672 #ifdef YOSYS_ENABLE_READLINE
673 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
675 char command_buffer
[4096];
676 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
679 if (command
[strspn(command
, " \t\r\n")] == 0)
681 #ifdef YOSYS_ENABLE_READLINE
682 add_history(command
);
685 char *p
= command
+ strspn(command
, " \t\r\n");
686 if (!strncmp(p
, "exit", 4)) {
688 p
+= strspn(p
, " \t\r\n");
694 log_assert(design
->selection_stack
.size() == 1);
695 Pass::call(design
, command
);
696 } catch (log_cmd_error_expection
) {
697 while (design
->selection_stack
.size() > 1)
698 design
->selection_stack
.pop_back();
706 log_cmd_error_throw
= false;
709 struct ShellPass
: public Pass
{
710 ShellPass() : Pass("shell", "enter interactive command mode") { }
711 virtual void help() {
715 log("This command enters the interactive command mode. This can be useful\n");
716 log("in a script to interrupt the script at a certain point and allow for\n");
717 log("interactive inspection or manual synthesis of the design at this point.\n");
719 log("The command prompt of the interactive shell indicates the current\n");
720 log("selection (see 'help select'):\n");
723 log(" the entire design is selected\n");
726 log(" only part of the design is selected\n");
728 log(" yosys [modname]>\n");
729 log(" the entire module 'modname' is selected using 'select -module modname'\n");
731 log(" yosys [modname]*>\n");
732 log(" only part of current module 'modname' is selected\n");
734 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
735 log("do not terminate yosys but return to the command prompt.\n");
737 log("This command is the default action if nothing else has been specified\n");
738 log("on the command line.\n");
740 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
743 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
744 extra_args(args
, 1, design
, false);
749 #ifdef YOSYS_ENABLE_READLINE
750 struct HistoryPass
: public Pass
{
751 HistoryPass() : Pass("history", "show last interactive commands") { }
752 virtual void help() {
756 log("This command prints all commands in the shell history buffer. This are\n");
757 log("all commands executed in an interactive session, but not the commands\n");
758 log("from executed scripts.\n");
761 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
762 extra_args(args
, 1, design
, false);
763 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
764 log("%s\n", (*list
)->line
);
769 struct ScriptPass
: public Pass
{
770 ScriptPass() : Pass("script", "execute commands from script file") { }
771 virtual void help() {
773 log(" script <filename> [<from_label>:<to_label>]\n");
775 log("This command executes the yosys commands in the specified file.\n");
777 log("The 2nd argument can be used to only execute the section of the\n");
778 log("file between the specified labels. An empty from label is synonymous\n");
779 log("for the beginning of the file and an empty to label is synonymous\n");
780 log("for the end of the file.\n");
782 log("If only one label is specified (without ':') then only the block\n");
783 log("marked with that label (until the next label) is executed.\n");
786 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
788 log_cmd_error("Missing script file.\n");
789 else if (args
.size() == 2)
790 run_frontend(args
[1], "script", design
, NULL
, NULL
);
791 else if (args
.size() == 3)
792 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
794 extra_args(args
, 2, design
, false);