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>
38 RTLIL::Design
*yosys_design
= NULL
;
40 #ifdef YOSYS_ENABLE_TCL
41 Tcl_Interp
*yosys_tcl_interp
= NULL
;
44 std::string
stringf(const char *fmt
, ...)
50 string
= vstringf(fmt
, ap
);
56 std::string
vstringf(const char *fmt
, va_list ap
)
66 str
= (char*)realloc(str
, sz
);
67 rc
= vsnprintf(str
, sz
, fmt
, apc
);
69 if (rc
>= 0 && rc
< sz
)
74 if (vasprintf(&str
, fmt
, ap
) < 0)
86 std::string
next_token(std::string
&text
, const char *sep
)
88 size_t pos_begin
= text
.find_first_not_of(sep
);
90 if (pos_begin
== std::string::npos
)
91 pos_begin
= text
.size();
93 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
95 if (pos_end
== std::string::npos
)
96 pos_end
= text
.size();
98 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
99 text
= text
.substr(pos_end
);
103 // this is very similar to fnmatch(). the exact rules used by this
106 // ? matches any character except
107 // * matches any sequence of characters
108 // [...] matches any of the characters in the list
109 // [!..] matches any of the characters not in the list
111 // a backslash may be used to escape the next characters in the
112 // pattern. each special character can also simply match itself.
114 bool patmatch(const char *pattern
, const char *string
)
119 if (*pattern
== '\\') {
120 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
124 if (*pattern
== '?') {
127 return patmatch(pattern
+1, string
+1);
130 if (*pattern
== '*') {
132 if (patmatch(pattern
+1, string
++))
135 return pattern
[1] == 0;
138 if (*pattern
== '[') {
139 bool found_match
= false;
140 bool inverted_list
= pattern
[1] == '!';
141 const char *p
= pattern
+ (inverted_list
? 1 : 0);
145 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
159 if (*pattern
== *string
)
160 return patmatch(pattern
+1, string
+1);
165 int GetSize(RTLIL::Wire
*wire
)
172 Pass::init_register();
173 yosys_design
= new RTLIL::Design
;
177 void yosys_shutdown()
184 for (auto f
: log_files
)
190 Pass::done_register();
192 #ifdef YOSYS_ENABLE_TCL
193 if (yosys_tcl_interp
!= NULL
) {
194 Tcl_DeleteInterp(yosys_tcl_interp
);
196 yosys_tcl_interp
= NULL
;
201 for (auto &it
: loaded_plugins
)
205 loaded_plugins
.clear();
206 loaded_plugin_aliases
.clear();
209 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
211 std::string str
= "$auto$";
212 size_t pos
= file
.find_last_of('/');
213 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
214 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
218 RTLIL::Design
*yosys_get_design()
223 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
225 static char buffer
[100];
226 std::string str
= "\n";
227 if (recursion_counter
> 1)
228 str
+= stringf("(%d) ", recursion_counter
);
230 if (!design
->selected_active_module
.empty())
231 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
232 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
233 if (design
->selected_active_module
.empty())
235 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
236 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
239 snprintf(buffer
, 100, "%s> ", str
.c_str());
243 #ifdef YOSYS_ENABLE_TCL
244 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
246 std::vector
<std::string
> args
;
247 for (int i
= 1; i
< argc
; i
++)
248 args
.push_back(argv
[i
]);
250 if (args
.size() >= 1 && args
[0] == "-import") {
251 for (auto &it
: pass_register
) {
252 std::string tcl_command_name
= it
.first
;
253 if (tcl_command_name
== "proc")
254 tcl_command_name
= "procs";
256 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
257 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
259 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
260 Tcl_Eval(interp
, tcl_script
.c_str());
266 if (args
.size() == 1) {
267 Pass::call(yosys_get_design(), args
[0]);
271 Pass::call(yosys_get_design(), args
);
275 extern Tcl_Interp
*yosys_get_tcl_interp()
277 if (yosys_tcl_interp
== NULL
) {
278 yosys_tcl_interp
= Tcl_CreateInterp();
279 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
281 return yosys_tcl_interp
;
284 struct TclPass
: public Pass
{
285 TclPass() : Pass("tcl", "execute a TCL script file") { }
286 virtual void help() {
288 log(" tcl <filename>\n");
290 log("This command executes the tcl commands in the specified file.\n");
291 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
293 log("The tcl command 'yosys -import' can be used to import all yosys\n");
294 log("commands directly as tcl commands to the tcl shell. The yosys\n");
295 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
296 log("to avoid a name collision with the tcl builting command 'proc'.\n");
299 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
301 log_cmd_error("Missing script file.\n");
303 extra_args(args
, 1, design
, false);
304 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
305 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
310 #if defined(__linux__)
311 std::string
proc_self_dirname()
313 char path
[PATH_MAX
];
314 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
316 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
318 while (buflen
> 0 && path
[buflen
-1] != '/')
320 return std::string(path
, buflen
);
322 #elif defined(__APPLE__)
323 #include <mach-o/dyld.h>
324 std::string
proc_self_dirname()
328 while (_NSGetExecutablePath(path
, &buflen
) != 0)
329 path
= (char *) realloc((void *) path
, buflen
);
330 while (buflen
> 0 && path
[buflen
-1] != '/')
332 return std::string(path
, buflen
);
334 #elif defined(_WIN32)
335 std::string
proc_self_dirname()
337 #warning Fixme: Implement proc_self_dirname() for win32.
338 log_error("proc_self_dirname() is not implemented for win32 yet!\n");
340 #elif defined(EMSCRIPTEN)
341 std::string
proc_self_dirname()
346 #error Dont know how to determine process executable base path!
349 std::string
proc_share_dirname()
351 std::string proc_self_path
= proc_self_dirname();
352 std::string proc_share_path
= proc_self_path
+ "share/";
353 if (access(proc_share_path
.c_str(), X_OK
) == 0)
354 return proc_share_path
;
355 proc_share_path
= proc_self_path
+ "../share/yosys/";
356 if (access(proc_share_path
.c_str(), X_OK
) == 0)
357 return proc_share_path
;
358 log_error("proc_share_dirname: unable to determine share/ directory!\n");
361 bool fgetline(FILE *f
, std::string
&buffer
)
366 if (fgets(block
, 4096, f
) == NULL
)
369 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
370 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
371 buffer
.resize(buffer
.size()-1);
377 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
382 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
385 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
386 label
+= command
[pos
++];
388 if (label
.back() == ':' && GetSize(label
) > 1)
390 label
= label
.substr(0, GetSize(label
)-1);
391 command
= command
.substr(pos
);
393 if (label
== run_from
)
394 from_to_active
= true;
395 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
396 from_to_active
= false;
400 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
402 if (command
== "auto") {
403 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
405 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
406 command
= "verilog -sv";
407 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
409 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
411 else if (filename
== "-")
414 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
417 if (command
== "script")
419 std::string run_from
, run_to
;
420 bool from_to_active
= true;
422 if (from_to_label
!= NULL
) {
423 size_t pos
= from_to_label
->find(':');
424 if (pos
== std::string::npos
) {
425 run_from
= *from_to_label
;
426 run_to
= *from_to_label
;
428 run_from
= from_to_label
->substr(0, pos
);
429 run_to
= from_to_label
->substr(pos
+1);
431 from_to_active
= run_from
.empty();
434 log("\n-- Executing script file `%s' --\n", filename
.c_str());
439 f
= fopen(filename
.c_str(), "r");
442 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
444 FILE *backup_script_file
= Frontend::current_script_file
;
445 Frontend::current_script_file
= f
;
449 while (fgetline(f
, command
)) {
450 while (!command
.empty() && command
[command
.size()-1] == '\\') {
451 std::string next_line
;
452 if (!fgetline(f
, next_line
))
454 command
.resize(command
.size()-1);
455 command
+= next_line
;
457 handle_label(command
, from_to_active
, run_from
, run_to
);
459 Pass::call(design
, command
);
462 if (!command
.empty()) {
463 handle_label(command
, from_to_active
, run_from
, run_to
);
465 Pass::call(design
, command
);
468 catch (log_cmd_error_expection
) {
469 Frontend::current_script_file
= backup_script_file
;
470 throw log_cmd_error_expection();
473 Frontend::current_script_file
= backup_script_file
;
478 if (backend_command
!= NULL
&& *backend_command
== "auto")
479 *backend_command
= "";
484 if (filename
== "-") {
485 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
487 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
490 Frontend::frontend_call(design
, NULL
, filename
, command
);
493 void run_pass(std::string command
, RTLIL::Design
*design
)
495 log("\n-- Running pass `%s' --\n", command
.c_str());
497 Pass::call(design
, command
);
500 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
502 if (command
== "auto") {
503 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
505 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
507 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
509 else if (filename
== "-")
511 else if (filename
.empty())
514 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
517 if (filename
.empty())
520 if (filename
== "-") {
521 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
523 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
526 Backend::backend_call(design
, NULL
, filename
, command
);
529 #ifdef YOSYS_ENABLE_READLINE
530 static char *readline_cmd_generator(const char *text
, int state
)
532 static std::map
<std::string
, Pass
*>::iterator it
;
536 it
= pass_register
.begin();
540 for (; it
!= pass_register
.end(); it
++) {
541 if (it
->first
.substr(0, len
) == text
)
542 return strdup((it
++)->first
.c_str());
547 static char *readline_obj_generator(const char *text
, int state
)
549 static std::vector
<char*> obj_names
;
557 RTLIL::Design
*design
= yosys_get_design();
558 int len
= strlen(text
);
560 if (design
->selected_active_module
.empty())
562 for (auto &it
: design
->modules_
)
563 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
564 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
567 if (design
->modules_
.count(design
->selected_active_module
) > 0)
569 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
571 for (auto &it
: module
->wires_
)
572 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
573 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
575 for (auto &it
: module
->memories
)
576 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
577 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
579 for (auto &it
: module
->cells_
)
580 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
581 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
583 for (auto &it
: module
->processes
)
584 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
585 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
588 std::sort(obj_names
.begin(), obj_names
.end());
591 if (idx
< obj_names
.size())
592 return strdup(obj_names
[idx
++]);
599 static char **readline_completion(const char *text
, int start
, int)
602 return rl_completion_matches(text
, readline_cmd_generator
);
603 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
604 return rl_completion_matches(text
, readline_obj_generator
);
609 void shell(RTLIL::Design
*design
)
611 static int recursion_counter
= 0;
614 log_cmd_error_throw
= true;
616 #ifdef YOSYS_ENABLE_READLINE
617 rl_readline_name
= "yosys";
618 rl_attempted_completion_function
= readline_completion
;
619 rl_basic_word_break_characters
= " \t\n";
622 char *command
= NULL
;
623 #ifdef YOSYS_ENABLE_READLINE
624 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
626 char command_buffer
[4096];
627 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
630 if (command
[strspn(command
, " \t\r\n")] == 0)
632 #ifdef YOSYS_ENABLE_READLINE
633 add_history(command
);
636 char *p
= command
+ strspn(command
, " \t\r\n");
637 if (!strncmp(p
, "exit", 4)) {
639 p
+= strspn(p
, " \t\r\n");
645 log_assert(design
->selection_stack
.size() == 1);
646 Pass::call(design
, command
);
647 } catch (log_cmd_error_expection
) {
648 while (design
->selection_stack
.size() > 1)
649 design
->selection_stack
.pop_back();
657 log_cmd_error_throw
= false;
660 struct ShellPass
: public Pass
{
661 ShellPass() : Pass("shell", "enter interactive command mode") { }
662 virtual void help() {
666 log("This command enters the interactive command mode. This can be useful\n");
667 log("in a script to interrupt the script at a certain point and allow for\n");
668 log("interactive inspection or manual synthesis of the design at this point.\n");
670 log("The command prompt of the interactive shell indicates the current\n");
671 log("selection (see 'help select'):\n");
674 log(" the entire design is selected\n");
677 log(" only part of the design is selected\n");
679 log(" yosys [modname]>\n");
680 log(" the entire module 'modname' is selected using 'select -module modname'\n");
682 log(" yosys [modname]*>\n");
683 log(" only part of current module 'modname' is selected\n");
685 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
686 log("do not terminate yosys but return to the command prompt.\n");
688 log("This command is the default action if nothing else has been specified\n");
689 log("on the command line.\n");
691 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
694 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
695 extra_args(args
, 1, design
, false);
700 #ifdef YOSYS_ENABLE_READLINE
701 struct HistoryPass
: public Pass
{
702 HistoryPass() : Pass("history", "show last interactive commands") { }
703 virtual void help() {
707 log("This command prints all commands in the shell history buffer. This are\n");
708 log("all commands executed in an interactive session, but not the commands\n");
709 log("from executed scripts.\n");
712 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
713 extra_args(args
, 1, design
, false);
714 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
715 log("%s\n", (*list
)->line
);
720 struct ScriptPass
: public Pass
{
721 ScriptPass() : Pass("script", "execute commands from script file") { }
722 virtual void help() {
724 log(" script <filename> [<from_label>:<to_label>]\n");
726 log("This command executes the yosys commands in the specified file.\n");
728 log("The 2nd argument can be used to only execute the section of the\n");
729 log("file between the specified labels. An empty from label is synonymous\n");
730 log("for the beginning of the file and an empty to label is synonymous\n");
731 log("for the end of the file.\n");
733 log("If only one label is specified (without ':') then only the block\n");
734 log("marked with that label (until the next label) is executed.\n");
737 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
739 log_cmd_error("Missing script file.\n");
740 else if (args
.size() == 2)
741 run_frontend(args
[1], "script", design
, NULL
, NULL
);
742 else if (args
.size() == 3)
743 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
745 extra_args(args
, 2, design
, false);