11

等效地,如何为“单个”UTF8 字符指定类型?

在类型定义中,我可以使用通用的“任何字符串”或“任何 utf8 字符串”

@type tile :: String.t # matches any string
@type tile :: <<_::8>> # matches any single byte

但似乎我无法匹配第一位为 0

@type tile :: <<0::1, _::7>>

单个 UTF 位序列的情况是

@type tile :: <<0::1, _::7>> | 
              <<6::3, _::5, 2::2, _::6>> | 
              <<14::4, _::4, 2::2, _::6, 2::2, _::6>> |
              <<30::5, _::3, 2::2, _::6, 2::2, _::6, 2::2, _::6>>

(例如,这些位模式在使用模式匹配时匹配

<<14::4, _::4, 2::2, _::6, 2::2, _::6>> = "○"

成功。)

但是当在 typespecs 中使用时,编译器会抱怨很多

== Compilation error in file lib/board.ex ==
** (ArgumentError) argument error
    (elixir) lib/kernel/typespec.ex:1000: Kernel.Typespec.typespec/3
    (elixir) lib/kernel/typespec.ex:1127: anonymous fn/4 in Kernel.Typespec.typespec/3
    (elixir) lib/enum.ex:1899: Enum."-reduce/3-lists^foldl/2-0-"/3
    (elixir) lib/kernel/typespec.ex:1127: Kernel.Typespec.typespec/3
    (elixir) lib/kernel/typespec.ex:828: anonymous fn/4 in Kernel.Typespec.typespec/3
    (elixir) lib/enum.ex:1899: Enum."-reduce/3-lists^foldl/2-0-"/3
    (elixir) lib/kernel/typespec.ex:828: Kernel.Typespec.typespec/3
    (elixir) lib/kernel/typespec.ex:470: Kernel.Typespec.translate_type/3

有没有办法对这样的位模式进行类型规范?

4

1 回答 1

1

您不能仅根据二进制的唯一事实对二进制模式进行类型规范。即使您可以定义此类规范,我也不认为 Dialyzer 足够复杂,无法在此类匹配中发现故障。您只剩下在运行时使用警卫和模式匹配来实现此类行为,例如:

def unicode?(<<0::size(1), a::size(7)>>), do: true
def unicode?(<<6::3, _::5, 2::2, _::6>>), do: true 
def unicode?(<<14::4, _::4, 2::2, _::6, 2::2, _::6>>), do: true
def unicode?(<<30::5, _::3, 2::2, _::6, 2::2, _::6, 2::2, _::6>>), do: true
def unicode?(str) when is_binary(str), do: false

不幸的是,据我所知,没有办法在守卫中使用位模式,您只能使用 匹配整个字节binary_part/3,但是没有功能可以对位执行相同的操作。所以你能得到的最接近的是这样的(未经测试这是否有效,甚至可以编译,但让你大致了解什么是可能的):

defguardp is_valid_utf_part(code) when code in 0b10000000..0b10111111

defguard is_unicode(<<ascii>>) when ascii in 0b0000000..0b01111111
defguard is_unicode(<<first, second>>)
  when first in 0b11000000..0b11011111
   and is_valid_utf_part(second)
defguard is_unicode(<<first, second, third>>)
  when first in 0b11100000..0b11101111
   and is_valid_utf_part(second)
   and is_valid_utf_part(third)
defguard is_unicode(<<first, second, third, fourth>>)
  when first in 0b11110000..0b11110111
   and is_valid_utf_part(second)
   and is_valid_utf_part(third)
   and is_valid_utf_part(fourth)
于 2018-11-13T13:54:37.537 回答