- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个用于解析 OVPN 配置文件的小库。 OVPN 配置文件具有这种格式
command arg1 arg2
othercommand arg1 arg2
有一组固定的命令,其中一些有可选参数。我想将解析的命令表示为枚举。所以上面的内容最终可能会这样表示:
enum ConfigDirective{
Command{arg1: String},
OtherCommand{arg1: String, optinal_arg1: Option<String>},
}
fn parse_line(command: String, args: Vec<String>) -> ConfigDirective {
match command {
"command" => ConfigDirective::Command{arg1: args[0]},
"other_command" => ConfigDirective:OtherCommand{arg1: args[0], optional_arg1: args.get(1),
}
}
我喜欢这种结构,但有很多可能的命令(大约 280 个)。所以我想写一个宏来生成大部分样板文件。理想情况下,我会写如下内容:
define_config_directive!{
{command => "command1", rust_name => CommandOne, args => [arg1], optional_args => []},
{command => "other_command", rust_name => OtherCommand, args => [arg1], optional_args => [optional_arg1]},
}
到目前为止我能得到的最接近的是:
macro_rules! define_config_directives {
($({
rust_name => $rust_name:ident,
required => [$($required:ident),*],
optional => [$($optional:ident),*]
}),*) => {
#[derive(PartialEq, Eq, Debug)]
pub enum ConfigDirective {
$($rust_name{
$($required: String),*,
$($optional: Option<String>),*,
}),*
}
};
}
所以我有几个问题:
parse_line
函数,我需要遍历每个必需的参数,以便编写一些代码将相应的参数从行中提取出来,并且相同可选参数有谁知道是否有办法在稳定的 rust 上解决这个问题?或者我应该只使用 python 脚本生成代码?
最佳答案
这是一个有点病态的案例。首先,您想以不同的方式处理输入的部分,而宏不擅长这些。更糟糕的是,您想结合生成枚举变体来执行此操作,而宏也不擅长。据我所知,综合起来只剩下一种方法:完全使用下推生成。
简短的版本是:将其分解为简单的匹配步骤,其中每个步骤处理一件事情,并将一件事情的输出添加到累加器(在本例中,$eout
和 $噘嘴
)。当您没有输入时,将累加器转储到您的输出中。
macro_rules! define_config_directive {
// Start rule.
// Note: `$(,)*` is a trick to eat any number of trailing commas.
( $( {$($cmd:tt)*} ),* $(,)*) => {
// This starts the parse, giving the initial state of the output
// (i.e. empty). Note that the commands come after the semicolon.
define_config_directive! { @parse {}, (args){}; $({$($cmd)*},)* }
};
// Termination rule: no more input.
(
@parse
// $eout will be the body of the enum.
{$($eout:tt)*},
// $pout will be the body of the `parse_line` match.
// We pass `args` explicitly to make sure all stages are using the
// *same* `args` (due to identifier hygiene).
($args:ident){$($pout:tt)*};
// See, nothing here?
) => {
#[derive(PartialEq, Eq, Debug)]
enum ConfigDirective {
$($eout)*
}
fn parse_line(command: &str, $args: &[&str]) -> ConfigDirective {
match command {
$($pout)*
_ => panic!("unknown command: {:?}", command)
}
}
};
// Rule for command with no arguments.
(
@parse {$($eout:tt)*}, ($pargs:ident){$($pout:tt)*};
{
command: $sname:expr,
rust_name: $rname:ident,
args: [],
optional_args: [] $(,)*
},
$($tail:tt)*
) => {
define_config_directive! {
@parse
{
$($eout)*
$rname,
},
($pargs){
$($pout)*
$sname => ConfigDirective::$rname,
};
$($tail)*
}
};
// Rule for other commands.
(
@parse {$($eout:tt)*}, ($pargs:ident){$($pout:tt)*};
{
command: $sname:expr,
rust_name: $rname:ident,
args: [$($args:ident),* $(,)*],
optional_args: [$($oargs:ident),* $(,)*] $(,)*
},
$($tail:tt)*
) => {
define_config_directive! {
@parse
{
$($eout)*
$rname { $( $args: String, )* $( $oargs: Option<String>, )* },
},
($pargs){
$($pout)*
$sname => {
// This trickery is because macros can't count with
// regular integers. We'll just use a mutable index
// instead.
let mut i = 0;
$(let $args = $pargs[i].into(); i += 1;)*
$(let $oargs = $pargs.get(i).map(|&s| s.into()); i += 1;)*
let _ = i; // avoid unused assignment warnings.
ConfigDirective::$rname {
$($args: $args,)*
$($oargs: $oargs,)*
}
},
};
$($tail)*
}
};
}
define_config_directive! {
{command: "command1", rust_name: CommandOne, args: [arg1], optional_args: []},
{command: "other_command", rust_name: OtherCommand, args: [arg1], optional_args: [optional_arg1]},
}
fn main() {
println!("{:?}", parse_line("command1", &["foo"]));
println!("{:?}", parse_line("other_command", &["foo"]));
println!("{:?}", parse_line("other_command", &["foo", "bar"]));
}
不,你无法避免累加器的事情,因为宏不能直接扩展为枚举变体。因此,您必须一步扩展到整个枚举定义。
关于macros - 如何使用 Rust 中的宏生成复杂的枚举变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44160750/
是否可以传递带有宏触发器的字符串作为宏参数?请参阅下面的示例代码: options mprint; %let string5='%abc%def%'; %macro test(string); dat
我意识到我的代码的某个部分由看起来相似的方法组组成(就像我有多个三重奏:一个辅助函数被另外两个为程序员准备的函数调用)。我正在尝试编写一个宏来为我定义这三个函数,这样我需要做的就是调用宏。但我的尝试导
这个问题在这里已经有了答案: What can you do with Lisp macros that you can't do with first-class functions? (8 个回答
在 haxe 宏中,对于每个表达式,我们可以以 http://api.haxe.org/haxe/macro/Position.html 的形式获取它的位置。 : { file:String,
如果我评价 (def ^:macro my-defn1 #'defn) 定义了一个名为“my-defn1”的宏,我可以像使用“defn”一样使用它。 但是,如果我改为求值 (if true (de
我想知道这段代码输出背后的原因。我想不出答案。 #define f(a,b) a##b #define g(a) #a #define h(a) g(a) void main() { print
我正在尝试编写一个宏,该宏扩展为具有解构的 let 形式。我的问题是我想拥有以 let 形式定义的符号列表,包括通过解构获得的符号列表。 用例 我试图排除这种行为,例如验证: (let [a (foo
这段代码: macro FL(message) return @sprintf("%s:%d | %s", @__FILE__, @__LINE__, message) # line 2 en
此宏的目的是创建一个宏,该宏为访问关联列表的某个键提供名称。 (defmacro generate-accessor (key-symbol prefix) (let ((mac-name
在mcpp.exe --help Options available with only -@std (default) option: -@compat Expand recursive ma
鉴于: (define-syntax (test stx) (syntax-case stx () [(_ body ...) (with-syntax ([body0 (pro
Doug Hoyte 在他对 Let Over Lambda 的介绍中将 symb 函数定义为使用宏进行元编程的基本实用程序: 在剪辑中: (defun mkstr (&rest args) (w
我的代码需要两种模式,debug 和 verbose。我在头文件中将它们定义为, #define verbose TRUE #define debug TRUE 到目前为止,在我的代码中,我一直在使用
Set-macro-character 有一个名为 non-terminating-p 的可选参数。好像是用来表示读完宏字符后是否要读另一个字符,但是reader algorithm似乎忽略了这个论点
我一直在搜索,但几乎找不到关于 LibreOffice Basic 的信息 我有点习惯在 excel 中编写宏,但这次需要做一个循环,直到我到达第一个空列并且它需要在 libreoffice 中。 在
我正在尝试编写一个调用某些函数的宏。这些函数只能由宏使用,因此我将它们放在包装宏的 letfn 中。伪代码: (letfn [(fn-a [] ...) (fn-b [] ...)
我发现对于任何在 clojure.tools.macro 中编写类似 defn 的宏的人来说,这将是一个很棒的工具。图书馆:name-with-attributes功能。文档字符串说: To be u
假设: (defmacro testing (&optional var) `(list 'this 'is ,@(when (consp var) `('a 'list)))
在 SBCL 中,我可以使用以下内容获取函数的文档字符串: (documentation #'mapcar t) 但是,我不明白如何获取宏的文档字符串。例如,给定宏: (defmacro with-l
想了解 undef 和将宏定义为 0 之间的区别。谢谢。 最佳答案 #define MACRO 0 定义预处理器标记 MACRO成为文字 0 #undef MACRO 删除预处理器标记 MACRO 的
我是一名优秀的程序员,十分优秀!