Skip to content

Commit

Permalink
Support Passing Python Variable for Module
Browse files Browse the repository at this point in the history
  • Loading branch information
Teddy-van-Jerry committed Mar 29, 2024
1 parent 3d21eb4 commit 804a34c
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Expand Up @@ -3,7 +3,7 @@ name = "pytv"
description = "Python Templated Verilog"
repository = "https://github.com/autohdw/pytv"
authors = ["Teddy van Jerry <me@teddy-van-jerry.org>"]
version = "0.4.0"
version = "0.5.0"
readme = "README.md"
license = "GPL-3.0-or-later"
keywords = ["verilog", "python", "template", "generation"]
Expand Down
4 changes: 2 additions & 2 deletions examples/D1.pytv
@@ -1,6 +1,6 @@
//! # port enable settings
//! if_rst = True
//! if_en = True
//! # parameter: if_rst = True
//! # parameter: if_en = True
// Delay by 1 clock
`timescale 1ns / 1ps

Expand Down
25 changes: 24 additions & 1 deletion src/config.rs
@@ -1,5 +1,6 @@
use clap::Parser;
use regex::Regex;
use std::error::Error;

/// Represents the configuration options for PyTV.
#[derive(Debug)]
Expand Down Expand Up @@ -38,6 +39,15 @@ impl Default for Config {
}
}

/// Parse a single key-value pair
fn parse_key_val(s: &str) -> Result<(String, String), Box<dyn Error>>
{
let pos = s
.find('=')
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
Ok((s[..pos].to_string(), s[pos + 1..].to_string()))
}

/// Python Templated Verilog
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
Expand Down Expand Up @@ -70,6 +80,9 @@ struct Args {
/// Magic comment string (after "//")
#[arg(short, long, default_value = "!", value_name = "STRING")]
magic: String,
/// Variables (multiple occurrences allowed)
#[arg(short, long = "var", value_name = "KEY=VAL")]
vars: Vec<String>,
}

impl Config {
Expand Down Expand Up @@ -100,8 +113,17 @@ impl Config {
}

/// Parses the command line arguments and returns a tuple of `Config` and `FileOptions`.
pub fn from_args() -> (Config, FileOptions) {
pub fn from_args() -> (Config, FileOptions, Option<Vec<(String, String)>>) {
let args = Args::parse();
let vars = args
.vars
.iter()
.map(|s| parse_key_val(s))
.collect::<Result<Vec<(String, String)>, Box<dyn Error>>>();
if vars.is_err() {
eprintln!("Error: {}", vars.err().unwrap());
std::process::exit(1);
}
(
Self::new(
args.magic,
Expand All @@ -114,6 +136,7 @@ impl Config {
input: args.input,
output: args.output,
},
vars.ok(),
)
}

Expand Down
14 changes: 11 additions & 3 deletions src/convert.rs
Expand Up @@ -13,6 +13,7 @@ use std::result::Result;
pub struct Convert {
config: Config,
file_options: FileOptions,
vars: Option<Vec<(String, String)>>,
}

#[derive(Debug, PartialEq)]
Expand All @@ -31,17 +32,18 @@ impl Default for LineType {

impl Convert {
/// Creates a new `Convert` instance with the given configuration and file options.
pub fn new(config: Config, file_options: FileOptions) -> Convert {
pub fn new(config: Config, file_options: FileOptions, vars: Option<Vec<(String, String)>>) -> Convert {
Convert {
config,
file_options,
vars,
}
}

/// Creates a new `Convert` instance by parsing command line arguments.
pub fn from_args() -> Convert {
let (config, file_options) = Config::from_args();
Convert::new(config, file_options)
let (config, file_options, vars) = Config::from_args();
Convert::new(config, file_options, vars)
}

/// Opens the input file and reads its contents as a string.
Expand Down Expand Up @@ -242,6 +244,12 @@ impl Convert {
let mut within_inst = false;
let mut inst_str = String::new();
#[cfg(feature = "inst")]
// print user-defined variables
if let Some(vars) = &self.vars {
for (name, value) in vars {
writeln!(stream, "{} = {}", name, value)?;
}
}
writeln!(
stream,
concat!(
Expand Down

0 comments on commit 804a34c

Please sign in to comment.