類別 SyntaxSuggest::ExplainSyntax

根據來源說明語法錯誤

範例

source = "def foo; puts 'lol'" # Note missing end
explain ExplainSyntax.new(
  code_lines: CodeLine.from_source(source)
).call
explain.errors.first
# => "Unmatched keyword, missing `end' ?"

如果無法透過詞彙計算來判斷錯誤,就會針對輸入執行剖析器,並傳回原始錯誤。

範例

source = "1 * " # Note missing a second number
explain ExplainSyntax.new(
  code_lines: CodeLine.from_source(source)
).call
explain.errors.first
# => "syntax error, unexpected end-of-input"

常數

INVERSE

公開類別方法

new(code_lines:) 按一下以切換來源
# File lib/syntax_suggest/explain_syntax.rb, line 54
def initialize(code_lines:)
  @code_lines = code_lines
  @left_right = LeftRightLexCount.new
  @missing = nil
end

公開實例方法

call() 按一下以切換來源
# File lib/syntax_suggest/explain_syntax.rb, line 60
def call
  @code_lines.each do |line|
    line.lex.each do |lex|
      @left_right.count_lex(lex)
    end
  end

  self
end
errors() 按一下以切換來源

傳回語法錯誤訊息的陣列

如果找不到遺失的配對,就會改用原始錯誤訊息

# File lib/syntax_suggest/explain_syntax.rb, line 109
def errors
  if missing.empty?
    return GetParseErrors.errors(@code_lines.map(&:original).join).uniq
  end

  missing.map { |miss| why(miss) }
end
missing() 按一下以切換來源

傳回遺失元素的陣列

例如:

ExplainSyntax.new(code_lines: lines).missing
# => ["}"]

這表示來源程式碼中遺失了「}`」字元

# File lib/syntax_suggest/explain_syntax.rb, line 79
def missing
  @missing ||= @left_right.missing
end
why(miss) 按一下以切換來源

將遺失的字串轉換為人類可以理解的說明。

範例

explain.why("}")
# => "Unmatched `{', missing `}' ?"
# File lib/syntax_suggest/explain_syntax.rb, line 91
def why(miss)
  case miss
  when "keyword"
    "Unmatched `end', missing keyword (`do', `def`, `if`, etc.) ?"
  when "end"
    "Unmatched keyword, missing `end' ?"
  else
    inverse = INVERSE.fetch(miss) {
      raise "Unknown explain syntax char or key: #{miss.inspect}"
    }
    "Unmatched `#{inverse}', missing `#{miss}' ?"
  end
end