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 GetSize(RTLIL::Wire
*wire
)
192 Pass::init_register();
193 yosys_design
= new RTLIL::Design
;
197 void yosys_shutdown()
204 for (auto f
: log_files
)
210 Pass::done_register();
212 #ifdef YOSYS_ENABLE_TCL
213 if (yosys_tcl_interp
!= NULL
) {
214 Tcl_DeleteInterp(yosys_tcl_interp
);
216 yosys_tcl_interp
= NULL
;
220 #ifdef YOSYS_ENABLE_PLUGINS
221 for (auto &it
: loaded_plugins
)
225 loaded_plugins
.clear();
226 loaded_plugin_aliases
.clear();
229 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
231 std::string str
= "$auto$";
232 size_t pos
= file
.find_last_of('/');
233 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
234 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
238 RTLIL::Design
*yosys_get_design()
243 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
245 static char buffer
[100];
246 std::string str
= "\n";
247 if (recursion_counter
> 1)
248 str
+= stringf("(%d) ", recursion_counter
);
250 if (!design
->selected_active_module
.empty())
251 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
252 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
253 if (design
->selected_active_module
.empty())
255 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
256 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
259 snprintf(buffer
, 100, "%s> ", str
.c_str());
263 #ifdef YOSYS_ENABLE_TCL
264 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
266 std::vector
<std::string
> args
;
267 for (int i
= 1; i
< argc
; i
++)
268 args
.push_back(argv
[i
]);
270 if (args
.size() >= 1 && args
[0] == "-import") {
271 for (auto &it
: pass_register
) {
272 std::string tcl_command_name
= it
.first
;
273 if (tcl_command_name
== "proc")
274 tcl_command_name
= "procs";
276 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
277 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
279 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
280 Tcl_Eval(interp
, tcl_script
.c_str());
286 if (args
.size() == 1) {
287 Pass::call(yosys_get_design(), args
[0]);
291 Pass::call(yosys_get_design(), args
);
295 extern Tcl_Interp
*yosys_get_tcl_interp()
297 if (yosys_tcl_interp
== NULL
) {
298 yosys_tcl_interp
= Tcl_CreateInterp();
299 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
301 return yosys_tcl_interp
;
304 struct TclPass
: public Pass
{
305 TclPass() : Pass("tcl", "execute a TCL script file") { }
306 virtual void help() {
308 log(" tcl <filename>\n");
310 log("This command executes the tcl commands in the specified file.\n");
311 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
313 log("The tcl command 'yosys -import' can be used to import all yosys\n");
314 log("commands directly as tcl commands to the tcl shell. The yosys\n");
315 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
316 log("to avoid a name collision with the tcl builting command 'proc'.\n");
319 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
321 log_cmd_error("Missing script file.\n");
323 extra_args(args
, 1, design
, false);
324 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
325 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
330 #if defined(__linux__)
331 std::string
proc_self_dirname()
334 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
336 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
338 while (buflen
> 0 && path
[buflen
-1] != '/')
340 return std::string(path
, buflen
);
342 #elif defined(__APPLE__)
343 #include <mach-o/dyld.h>
344 std::string
proc_self_dirname()
348 while (_NSGetExecutablePath(path
, &buflen
) != 0)
349 path
= (char *) realloc((void *) path
, buflen
);
350 while (buflen
> 0 && path
[buflen
-1] != '/')
352 return std::string(path
, buflen
);
354 #elif defined(_WIN32)
355 std::string
proc_self_dirname()
357 char path
[MAX_PATH
+1];
358 if (!GetModuleFileName(0, path
, MAX_PATH
+1))
359 log_error("GetModuleFileName() failed.\n");
360 for (int i
= strlen(path
)-1; i
>= 0 && path
[i
] != '/' && path
[i
] != '\\' ; i
--)
362 return std::string(path
);
364 #elif defined(EMSCRIPTEN)
365 std::string
proc_self_dirname()
370 #error Dont know how to determine process executable base path!
373 std::string
proc_share_dirname()
375 std::string proc_self_path
= proc_self_dirname();
376 std::string proc_share_path
= proc_self_path
+ "share/";
377 if (access(proc_share_path
.c_str(), X_OK
) == 0)
378 return proc_share_path
;
379 proc_share_path
= proc_self_path
+ "../share/yosys/";
380 if (access(proc_share_path
.c_str(), X_OK
) == 0)
381 return proc_share_path
;
382 log_error("proc_share_dirname: unable to determine share/ directory!\n");
385 bool fgetline(FILE *f
, std::string
&buffer
)
390 if (fgets(block
, 4096, f
) == NULL
)
393 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
394 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
395 buffer
.resize(buffer
.size()-1);
401 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
406 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
409 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
410 label
+= command
[pos
++];
412 if (label
.back() == ':' && GetSize(label
) > 1)
414 label
= label
.substr(0, GetSize(label
)-1);
415 command
= command
.substr(pos
);
417 if (label
== run_from
)
418 from_to_active
= true;
419 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
420 from_to_active
= false;
424 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
426 if (command
== "auto") {
427 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
429 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
430 command
= "verilog -sv";
431 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
433 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
435 else if (filename
== "-")
438 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
441 if (command
== "script")
443 std::string run_from
, run_to
;
444 bool from_to_active
= true;
446 if (from_to_label
!= NULL
) {
447 size_t pos
= from_to_label
->find(':');
448 if (pos
== std::string::npos
) {
449 run_from
= *from_to_label
;
450 run_to
= *from_to_label
;
452 run_from
= from_to_label
->substr(0, pos
);
453 run_to
= from_to_label
->substr(pos
+1);
455 from_to_active
= run_from
.empty();
458 log("\n-- Executing script file `%s' --\n", filename
.c_str());
463 f
= fopen(filename
.c_str(), "r");
466 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
468 FILE *backup_script_file
= Frontend::current_script_file
;
469 Frontend::current_script_file
= f
;
473 while (fgetline(f
, command
)) {
474 while (!command
.empty() && command
[command
.size()-1] == '\\') {
475 std::string next_line
;
476 if (!fgetline(f
, next_line
))
478 command
.resize(command
.size()-1);
479 command
+= next_line
;
481 handle_label(command
, from_to_active
, run_from
, run_to
);
483 Pass::call(design
, command
);
486 if (!command
.empty()) {
487 handle_label(command
, from_to_active
, run_from
, run_to
);
489 Pass::call(design
, command
);
492 catch (log_cmd_error_expection
) {
493 Frontend::current_script_file
= backup_script_file
;
494 throw log_cmd_error_expection();
497 Frontend::current_script_file
= backup_script_file
;
502 if (backend_command
!= NULL
&& *backend_command
== "auto")
503 *backend_command
= "";
508 if (filename
== "-") {
509 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
511 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
514 Frontend::frontend_call(design
, NULL
, filename
, command
);
517 void run_pass(std::string command
, RTLIL::Design
*design
)
519 log("\n-- Running pass `%s' --\n", command
.c_str());
521 Pass::call(design
, command
);
524 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
526 if (command
== "auto") {
527 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
529 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
531 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
533 else if (filename
== "-")
535 else if (filename
.empty())
538 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
541 if (filename
.empty())
544 if (filename
== "-") {
545 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
547 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
550 Backend::backend_call(design
, NULL
, filename
, command
);
553 #ifdef YOSYS_ENABLE_READLINE
554 static char *readline_cmd_generator(const char *text
, int state
)
556 static std::map
<std::string
, Pass
*>::iterator it
;
560 it
= pass_register
.begin();
564 for (; it
!= pass_register
.end(); it
++) {
565 if (it
->first
.substr(0, len
) == text
)
566 return strdup((it
++)->first
.c_str());
571 static char *readline_obj_generator(const char *text
, int state
)
573 static std::vector
<char*> obj_names
;
581 RTLIL::Design
*design
= yosys_get_design();
582 int len
= strlen(text
);
584 if (design
->selected_active_module
.empty())
586 for (auto &it
: design
->modules_
)
587 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
588 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
591 if (design
->modules_
.count(design
->selected_active_module
) > 0)
593 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
595 for (auto &it
: module
->wires_
)
596 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
597 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
599 for (auto &it
: module
->memories
)
600 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
601 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
603 for (auto &it
: module
->cells_
)
604 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
605 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
607 for (auto &it
: module
->processes
)
608 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
609 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
612 std::sort(obj_names
.begin(), obj_names
.end());
615 if (idx
< obj_names
.size())
616 return strdup(obj_names
[idx
++]);
623 static char **readline_completion(const char *text
, int start
, int)
626 return rl_completion_matches(text
, readline_cmd_generator
);
627 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
628 return rl_completion_matches(text
, readline_obj_generator
);
633 void shell(RTLIL::Design
*design
)
635 static int recursion_counter
= 0;
638 log_cmd_error_throw
= true;
640 #ifdef YOSYS_ENABLE_READLINE
641 rl_readline_name
= "yosys";
642 rl_attempted_completion_function
= readline_completion
;
643 rl_basic_word_break_characters
= " \t\n";
646 char *command
= NULL
;
647 #ifdef YOSYS_ENABLE_READLINE
648 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
650 char command_buffer
[4096];
651 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
654 if (command
[strspn(command
, " \t\r\n")] == 0)
656 #ifdef YOSYS_ENABLE_READLINE
657 add_history(command
);
660 char *p
= command
+ strspn(command
, " \t\r\n");
661 if (!strncmp(p
, "exit", 4)) {
663 p
+= strspn(p
, " \t\r\n");
669 log_assert(design
->selection_stack
.size() == 1);
670 Pass::call(design
, command
);
671 } catch (log_cmd_error_expection
) {
672 while (design
->selection_stack
.size() > 1)
673 design
->selection_stack
.pop_back();
681 log_cmd_error_throw
= false;
684 struct ShellPass
: public Pass
{
685 ShellPass() : Pass("shell", "enter interactive command mode") { }
686 virtual void help() {
690 log("This command enters the interactive command mode. This can be useful\n");
691 log("in a script to interrupt the script at a certain point and allow for\n");
692 log("interactive inspection or manual synthesis of the design at this point.\n");
694 log("The command prompt of the interactive shell indicates the current\n");
695 log("selection (see 'help select'):\n");
698 log(" the entire design is selected\n");
701 log(" only part of the design is selected\n");
703 log(" yosys [modname]>\n");
704 log(" the entire module 'modname' is selected using 'select -module modname'\n");
706 log(" yosys [modname]*>\n");
707 log(" only part of current module 'modname' is selected\n");
709 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
710 log("do not terminate yosys but return to the command prompt.\n");
712 log("This command is the default action if nothing else has been specified\n");
713 log("on the command line.\n");
715 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
718 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
719 extra_args(args
, 1, design
, false);
724 #ifdef YOSYS_ENABLE_READLINE
725 struct HistoryPass
: public Pass
{
726 HistoryPass() : Pass("history", "show last interactive commands") { }
727 virtual void help() {
731 log("This command prints all commands in the shell history buffer. This are\n");
732 log("all commands executed in an interactive session, but not the commands\n");
733 log("from executed scripts.\n");
736 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
737 extra_args(args
, 1, design
, false);
738 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
739 log("%s\n", (*list
)->line
);
744 struct ScriptPass
: public Pass
{
745 ScriptPass() : Pass("script", "execute commands from script file") { }
746 virtual void help() {
748 log(" script <filename> [<from_label>:<to_label>]\n");
750 log("This command executes the yosys commands in the specified file.\n");
752 log("The 2nd argument can be used to only execute the section of the\n");
753 log("file between the specified labels. An empty from label is synonymous\n");
754 log("for the beginning of the file and an empty to label is synonymous\n");
755 log("for the end of the file.\n");
757 log("If only one label is specified (without ':') then only the block\n");
758 log("marked with that label (until the next label) is executed.\n");
761 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
763 log_cmd_error("Missing script file.\n");
764 else if (args
.size() == 2)
765 run_frontend(args
[1], "script", design
, NULL
, NULL
);
766 else if (args
.size() == 3)
767 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
769 extra_args(args
, 2, design
, false);