【问题标题】:Scala: How to escape a backtick in a literal?Scala:如何逃避文字中的反引号?
【发布时间】:2019-04-05 16:42:03
【问题描述】:

Scala 中的文字允许定义标识符,正如 answer 所描述的那样。有没有办法在文字中逃避反引号`?执行以下操作:

 val `hello `world` = "hello world"

更新
其中一个用例是将refined 库用于匹配包含反引号的正则表达式的一些精炼类型,例如:

  import eu.timepit.refined._
  import eu.timepit.refined.api.Refined

  type MatchesRegexWithBacktick = String Refined MatchesRegex[W.`(a|`)`.T]

【问题讨论】:

  • 为什么不能使用任何不同的符号,例如撇号val `hello 'world` = "hello world"
  • 简短的回答是我正在使用refined 库。而且我想定义一种与正则表达式匹配的特定类型,并且正则表达式包含反引号...String Refined MatchesRegex[W.someRegexWithBackTick.T](我不得不删除 someRegexWithBackTick 周围的反引号,因为它破坏了格式)
  • 长答案是there @DmytroMitin

标签: scala literals


【解决方案1】:

Scala 编译器无法按原样完成,但也许可以使用改变标识符解析方式的编译器插件(也许如果反引号的函数是以某种方式替换为一些晦涩的 unicode 字符)。

Scala SLS 1.1中,有标识符的词法语法:

op       ::=  opchar {opchar}
varid    ::=  lower idrest
boundvarid ::=  varid
             | ‘`’ varid ‘`’
plainid  ::=  upper idrest
           |  varid
           |  op
id       ::=  plainid
           |  ‘`’ { charNoBackQuoteOrNewline | UnicodeEscape | charEscapeSeq } ‘`’
idrest   ::=  {letter | digit} [‘_’ op]

问题是,允许除字母、数字或_ 之外的任何字符的唯一规则是要求标识符用反引号引起来:

‘`’ { charNoBackQuoteOrNewline | UnicodeEscape | charEscapeSeq } ‘`’

但是,它明确不允许使用 charNoBackQuoteOrNewline 进行反引号,如果您认为可以使用 UnicodeEscape 解决它,那也不起作用:

scala> val `hello \u0060world` = "hello world"
<console>:1: error: unclosed quoted identifier
val `hello \u0060world` = "hello world"
                      ^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    相关资源
    最近更新 更多