Preparations for RTLIL::IdString redesign: cleanup of existing code
[yosys.git] / kernel / yosys.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
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.
9 *
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.
17 *
18 */
19
20 #include "kernel/yosys.h"
21
22 #include <readline/readline.h>
23 #include <readline/history.h>
24
25 #include <unistd.h>
26 #include <limits.h>
27
28 YOSYS_NAMESPACE_BEGIN
29
30 int autoidx = 1;
31 RTLIL::Design *yosys_design = NULL;
32
33 #ifdef YOSYS_ENABLE_TCL
34 Tcl_Interp *yosys_tcl_interp = NULL;
35 #endif
36
37 std::string stringf(const char *fmt, ...)
38 {
39 std::string string;
40 va_list ap;
41
42 va_start(ap, fmt);
43 string = vstringf(fmt, ap);
44 va_end(ap);
45
46 return string;
47 }
48
49 std::string vstringf(const char *fmt, va_list ap)
50 {
51 std::string string;
52 char *str = NULL;
53
54 if (vasprintf(&str, fmt, ap) < 0)
55 str = NULL;
56
57 if (str != NULL) {
58 string = str;
59 free(str);
60 }
61
62 return string;
63 }
64
65 int SIZE(RTLIL::Wire *wire)
66 {
67 return wire->width;
68 }
69
70 void yosys_setup()
71 {
72 Pass::init_register();
73
74 yosys_design = new RTLIL::Design;
75 yosys_design->selection_stack.push_back(RTLIL::Selection());
76 log_push();
77 }
78
79 void yosys_shutdown()
80 {
81 log_pop();
82
83 delete yosys_design;
84 yosys_design = NULL;
85
86 for (auto f : log_files)
87 if (f != stderr)
88 fclose(f);
89 log_errfile = NULL;
90 log_files.clear();
91
92 Pass::done_register();
93
94 #ifdef YOSYS_ENABLE_TCL
95 if (yosys_tcl_interp != NULL) {
96 Tcl_DeleteInterp(yosys_tcl_interp);
97 Tcl_Finalize();
98 yosys_tcl_interp = NULL;
99 }
100 #endif
101 }
102
103 RTLIL::IdString new_id(std::string file, int line, std::string func)
104 {
105 std::string str = "$auto$";
106 size_t pos = file.find_last_of('/');
107 str += pos != std::string::npos ? file.substr(pos+1) : file;
108 str += stringf(":%d:%s$%d", line, func.c_str(), autoidx++);
109 return str;
110 }
111
112 RTLIL::Design *yosys_get_design()
113 {
114 return yosys_design;
115 }
116
117 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
118 {
119 static char buffer[100];
120 std::string str = "\n";
121 if (recursion_counter > 1)
122 str += stringf("(%d) ", recursion_counter);
123 str += "yosys";
124 if (!design->selected_active_module.empty())
125 str += stringf(" [%s]", RTLIL::id2cstr(design->selected_active_module));
126 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
127 if (design->selected_active_module.empty())
128 str += "*";
129 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
130 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
131 str += "*";
132 }
133 snprintf(buffer, 100, "%s> ", str.c_str());
134 return buffer;
135 }
136
137 #ifdef YOSYS_ENABLE_TCL
138 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
139 {
140 std::vector<std::string> args;
141 for (int i = 1; i < argc; i++)
142 args.push_back(argv[i]);
143
144 if (args.size() >= 1 && args[0] == "-import") {
145 for (auto &it : pass_register) {
146 std::string tcl_command_name = it.first;
147 if (tcl_command_name == "proc")
148 tcl_command_name = "procs";
149 Tcl_CmdInfo info;
150 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
151 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
152 } else {
153 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
154 Tcl_Eval(interp, tcl_script.c_str());
155 }
156 }
157 return TCL_OK;
158 }
159
160 if (args.size() == 1) {
161 Pass::call(yosys_get_design(), args[0]);
162 return TCL_OK;
163 }
164
165 Pass::call(yosys_get_design(), args);
166 return TCL_OK;
167 }
168
169 extern Tcl_Interp *yosys_get_tcl_interp()
170 {
171 if (yosys_tcl_interp == NULL) {
172 yosys_tcl_interp = Tcl_CreateInterp();
173 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
174 }
175 return yosys_tcl_interp;
176 }
177
178 struct TclPass : public Pass {
179 TclPass() : Pass("tcl", "execute a TCL script file") { }
180 virtual void help() {
181 log("\n");
182 log(" tcl <filename>\n");
183 log("\n");
184 log("This command executes the tcl commands in the specified file.\n");
185 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
186 log("\n");
187 log("The tcl command 'yosys -import' can be used to import all yosys\n");
188 log("commands directly as tcl commands to the tcl shell. The yosys\n");
189 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
190 log("to avoid a name collision with the tcl builting command 'proc'.\n");
191 log("\n");
192 }
193 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
194 if (args.size() < 2)
195 log_cmd_error("Missing script file.\n");
196 if (args.size() > 2)
197 extra_args(args, 1, design, false);
198 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
199 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
200 }
201 } TclPass;
202 #endif
203
204 #if defined(__linux__)
205 std::string proc_self_dirname ()
206 {
207 char path [PATH_MAX];
208 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
209 if (buflen < 0) {
210 log_cmd_error("readlink(\"/proc/self/exe\") failed: %s", strerror(errno));
211 log_abort();
212 }
213 while (buflen > 0 && path[buflen-1] != '/')
214 buflen--;
215 return std::string(path, buflen);
216 }
217 #elif defined(__APPLE__)
218 #include <mach-o/dyld.h>
219 std::string proc_self_dirname ()
220 {
221 char * path = NULL;
222 uint32_t buflen = 0;
223 while (_NSGetExecutablePath(path, &buflen) != 0)
224 path = (char *) realloc((void *) path, buflen);
225 while (buflen > 0 && path[buflen-1] != '/')
226 buflen--;
227 return std::string(path, buflen);
228 }
229 #else
230 #error Dont know how to determine process executable base path!
231 #endif
232
233 std::string proc_share_dirname ()
234 {
235 std::string proc_self_path = proc_self_dirname();
236 std::string proc_share_path = proc_self_path + "share/";
237 if (access(proc_share_path.c_str(), X_OK) == 0)
238 return proc_share_path;
239 proc_share_path = proc_self_path + "../share/yosys/";
240 if (access(proc_share_path.c_str(), X_OK) == 0)
241 return proc_share_path;
242 log_cmd_error("proc_share_dirname: unable to determine share/ directory!");
243 log_abort();
244 }
245
246 bool fgetline(FILE *f, std::string &buffer)
247 {
248 buffer = "";
249 char block[4096];
250 while (1) {
251 if (fgets(block, 4096, f) == NULL)
252 return false;
253 buffer += block;
254 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
255 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
256 buffer.resize(buffer.size()-1);
257 return true;
258 }
259 }
260 }
261
262 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
263 {
264 int pos = 0;
265 std::string label;
266
267 while (pos < SIZE(command) && (command[pos] == ' ' || command[pos] == '\t'))
268 pos++;
269
270 while (pos < SIZE(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
271 label += command[pos++];
272
273 if (label.back() == ':' && SIZE(label) > 1)
274 {
275 label = label.substr(0, SIZE(label)-1);
276 command = command.substr(pos);
277
278 if (label == run_from)
279 from_to_active = true;
280 else if (label == run_to || (run_from == run_to && !run_from.empty()))
281 from_to_active = false;
282 }
283 }
284
285 void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command, std::string *from_to_label)
286 {
287 if (command == "auto") {
288 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
289 command = "verilog";
290 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
291 command = "verilog -sv";
292 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
293 command = "ilang";
294 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
295 command = "script";
296 else if (filename == "-")
297 command = "script";
298 else
299 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
300 }
301
302 if (command == "script")
303 {
304 std::string run_from, run_to;
305 bool from_to_active = true;
306
307 if (from_to_label != NULL) {
308 size_t pos = from_to_label->find(':');
309 if (pos == std::string::npos) {
310 run_from = *from_to_label;
311 run_to = *from_to_label;
312 } else {
313 run_from = from_to_label->substr(0, pos);
314 run_to = from_to_label->substr(pos+1);
315 }
316 from_to_active = run_from.empty();
317 }
318
319 log("\n-- Executing script file `%s' --\n", filename.c_str());
320
321 FILE *f = stdin;
322
323 if (filename != "-")
324 f = fopen(filename.c_str(), "r");
325
326 if (f == NULL)
327 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
328
329 FILE *backup_script_file = Frontend::current_script_file;
330 Frontend::current_script_file = f;
331
332 try {
333 std::string command;
334 while (fgetline(f, command)) {
335 while (!command.empty() && command[command.size()-1] == '\\') {
336 std::string next_line;
337 if (!fgetline(f, next_line))
338 break;
339 command.resize(command.size()-1);
340 command += next_line;
341 }
342 handle_label(command, from_to_active, run_from, run_to);
343 if (from_to_active)
344 Pass::call(design, command);
345 }
346
347 if (!command.empty()) {
348 handle_label(command, from_to_active, run_from, run_to);
349 if (from_to_active)
350 Pass::call(design, command);
351 }
352 }
353 catch (log_cmd_error_expection) {
354 Frontend::current_script_file = backup_script_file;
355 throw log_cmd_error_expection();
356 }
357
358 Frontend::current_script_file = backup_script_file;
359
360 if (filename != "-")
361 fclose(f);
362
363 if (backend_command != NULL && *backend_command == "auto")
364 *backend_command = "";
365
366 return;
367 }
368
369 if (filename == "-") {
370 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
371 } else {
372 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
373 }
374
375 Frontend::frontend_call(design, NULL, filename, command);
376 }
377
378 void run_pass(std::string command, RTLIL::Design *design)
379 {
380 log("\n-- Running pass `%s' --\n", command.c_str());
381
382 Pass::call(design, command);
383 }
384
385 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
386 {
387 if (command == "auto") {
388 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
389 command = "verilog";
390 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
391 command = "ilang";
392 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
393 command = "blif";
394 else if (filename == "-")
395 command = "ilang";
396 else if (filename.empty())
397 return;
398 else
399 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
400 }
401
402 if (filename.empty())
403 filename = "-";
404
405 if (filename == "-") {
406 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
407 } else {
408 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
409 }
410
411 Backend::backend_call(design, NULL, filename, command);
412 }
413
414 static char *readline_cmd_generator(const char *text, int state)
415 {
416 static std::map<std::string, Pass*>::iterator it;
417 static int len;
418
419 if (!state) {
420 it = pass_register.begin();
421 len = strlen(text);
422 }
423
424 for (; it != pass_register.end(); it++) {
425 if (it->first.substr(0, len) == text)
426 return strdup((it++)->first.c_str());
427 }
428 return NULL;
429 }
430
431 static char *readline_obj_generator(const char *text, int state)
432 {
433 static std::vector<char*> obj_names;
434 static size_t idx;
435
436 if (!state)
437 {
438 idx = 0;
439 obj_names.clear();
440
441 RTLIL::Design *design = yosys_get_design();
442 int len = strlen(text);
443
444 if (design->selected_active_module.empty())
445 {
446 for (auto &it : design->modules_)
447 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
448 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
449 }
450 else
451 if (design->modules_.count(design->selected_active_module) > 0)
452 {
453 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
454
455 for (auto &it : module->wires_)
456 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
457 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
458
459 for (auto &it : module->memories)
460 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
461 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
462
463 for (auto &it : module->cells_)
464 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
465 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
466
467 for (auto &it : module->processes)
468 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
469 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
470 }
471
472 std::sort(obj_names.begin(), obj_names.end());
473 }
474
475 if (idx < obj_names.size())
476 return strdup(obj_names[idx++]);
477
478 idx = 0;
479 obj_names.clear();
480 return NULL;
481 }
482
483 static char **readline_completion(const char *text, int start, int)
484 {
485 if (start == 0)
486 return rl_completion_matches(text, readline_cmd_generator);
487 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
488 return rl_completion_matches(text, readline_obj_generator);
489 return NULL;
490 }
491
492 void shell(RTLIL::Design *design)
493 {
494 static int recursion_counter = 0;
495
496 recursion_counter++;
497 log_cmd_error_throw = true;
498
499 rl_readline_name = "yosys";
500 rl_attempted_completion_function = readline_completion;
501 rl_basic_word_break_characters = " \t\n";
502
503 char *command = NULL;
504 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
505 {
506 if (command[strspn(command, " \t\r\n")] == 0)
507 continue;
508 add_history(command);
509
510 char *p = command + strspn(command, " \t\r\n");
511 if (!strncmp(p, "exit", 4)) {
512 p += 4;
513 p += strspn(p, " \t\r\n");
514 if (*p == 0)
515 break;
516 }
517
518 try {
519 log_assert(design->selection_stack.size() == 1);
520 Pass::call(design, command);
521 } catch (log_cmd_error_expection) {
522 while (design->selection_stack.size() > 1)
523 design->selection_stack.pop_back();
524 log_reset_stack();
525 }
526 }
527 if (command == NULL)
528 printf("exit\n");
529
530 recursion_counter--;
531 log_cmd_error_throw = false;
532 }
533
534 struct ShellPass : public Pass {
535 ShellPass() : Pass("shell", "enter interactive command mode") { }
536 virtual void help() {
537 log("\n");
538 log(" shell\n");
539 log("\n");
540 log("This command enters the interactive command mode. This can be useful\n");
541 log("in a script to interrupt the script at a certain point and allow for\n");
542 log("interactive inspection or manual synthesis of the design at this point.\n");
543 log("\n");
544 log("The command prompt of the interactive shell indicates the current\n");
545 log("selection (see 'help select'):\n");
546 log("\n");
547 log(" yosys>\n");
548 log(" the entire design is selected\n");
549 log("\n");
550 log(" yosys*>\n");
551 log(" only part of the design is selected\n");
552 log("\n");
553 log(" yosys [modname]>\n");
554 log(" the entire module 'modname' is selected using 'select -module modname'\n");
555 log("\n");
556 log(" yosys [modname]*>\n");
557 log(" only part of current module 'modname' is selected\n");
558 log("\n");
559 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
560 log("do not terminate yosys but return to the command prompt.\n");
561 log("\n");
562 log("This command is the default action if nothing else has been specified\n");
563 log("on the command line.\n");
564 log("\n");
565 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
566 log("\n");
567 }
568 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
569 extra_args(args, 1, design, false);
570 shell(design);
571 }
572 } ShellPass;
573
574 struct HistoryPass : public Pass {
575 HistoryPass() : Pass("history", "show last interactive commands") { }
576 virtual void help() {
577 log("\n");
578 log(" history\n");
579 log("\n");
580 log("This command prints all commands in the shell history buffer. This are\n");
581 log("all commands executed in an interactive session, but not the commands\n");
582 log("from executed scripts.\n");
583 log("\n");
584 }
585 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
586 extra_args(args, 1, design, false);
587 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
588 log("%s\n", (*list)->line);
589 }
590 } HistoryPass;
591
592 struct ScriptPass : public Pass {
593 ScriptPass() : Pass("script", "execute commands from script file") { }
594 virtual void help() {
595 log("\n");
596 log(" script <filename> [<from_label>:<to_label>]\n");
597 log("\n");
598 log("This command executes the yosys commands in the specified file.\n");
599 log("\n");
600 log("The 2nd argument can be used to only execute the section of the\n");
601 log("file between the specified labels. An empty from label is synonymous\n");
602 log("for the beginning of the file and an empty to label is synonymous\n");
603 log("for the end of the file.\n");
604 log("\n");
605 log("If only one label is specified (without ':') then only the block\n");
606 log("marked with that label (until the next label) is executed.\n");
607 log("\n");
608 }
609 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
610 if (args.size() < 2)
611 log_cmd_error("Missing script file.\n");
612 else if (args.size() == 2)
613 run_frontend(args[1], "script", design, NULL, NULL);
614 else if (args.size() == 3)
615 run_frontend(args[1], "script", design, NULL, &args[2]);
616 else
617 extra_args(args, 2, design, false);
618 }
619 } ScriptPass;
620
621 YOSYS_NAMESPACE_END
622