[英]How do I write a spec for a function that contains special characters?
I have some macros that define functions that have special characters.我有一些宏定义了具有特殊字符的函数。 Specifically ":" and ".".
特别是“:”和“。”。 Is it possible to write a spec definition for functions with those characters in it?
是否可以为其中包含这些字符的函数编写规范定义?
defmodule UniqueCharacters do
defmacro make_wild_function_name do
function_name = String.to_atom("baz:foo.bar")
quote do
def unquote(function_name)(), do: :ok
end
end
end
defmodule TestSpec do
import UniqueCharacters
#This next line doesn't work
@spec baz:foo.bar() :: :ok
make_wild_function_name()
end
This produces the following error:这会产生以下错误:
** (SyntaxError) lib/unique_characters.ex:14: keyword argument must be followed by space after: baz:
(elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7
Is there a way to escape the characters in the function spec so that this will compile without removing the spec?有没有办法转义 function 规范中的字符,以便在不删除规范的情况下编译? I can change the ":" to "_" or something more well behaved but the "."
我可以将“:”更改为“_”或其他更好的东西,但“。” is basically non-negotiable.
基本没有商量余地。
Can you specify the typespec in your macro?您可以在宏中指定类型规范吗? If so, this seems to work fine:
如果是这样,这似乎工作正常:
defmodule UniqueCharacters do
defmacro make_wild_function_name do
function_name = String.to_atom("baz:foo.bar")
quote do
@spec unquote(function_name)() :: :ok
def unquote(function_name)(), do: :ok
end
end
end
defmodule TestSpec do
import UniqueCharacters
make_wild_function_name()
end
I feel like bundling the typespec with the definition makes the most sense;我觉得将 typespec 与定义捆绑在一起是最有意义的。 is that enough?
够了吗?
Edit: Looks like this also works, although kinda messy:编辑:看起来这也有效,虽然有点乱:
defmodule UniqueCharacters do
defmacro make_wild_function_name do
function_name = String.to_atom("baz:foo.bar")
quote do
def unquote(function_name)(), do: :ok
end
end
end
defmodule TestSpec do
import UniqueCharacters
@spec unquote(:'baz:foo.bar')() :: :ok
make_wild_function_name()
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.