class Pedant::CheckEqualityWithRegex

Public Class Methods

requires() click to toggle source
Calls superclass method Pedant::Check::requires
# File lib/pedant/checks/equality_with_regex.rb, line 29
def self.requires
  super + [:trees]
end

Public Instance Methods

check(file, tree) click to toggle source
# File lib/pedant/checks/equality_with_regex.rb, line 33
def check(file, tree)
  def walk(node, root)
    # Recursively descend into the right-hand and left-hand sides of each expression.
    if node.is_a? Nasl::Expression
      [:lhs, :rhs].each { |side| walk(node.send(side), root) }

      return unless node.op.is_a?(Nasl::Token)
      return unless ["==", "!="].include?(node.op.body)
      return unless node.rhs.is_a?(Nasl::String)
      str = node.rhs.text
      return unless str.length > 2
      return unless str[0] == "^" and str[-1] == "$"

      fail
      report(:error, "An equality comparison is being made with what appears to be a regex.")
      report(:error, "This might be a typo in the operator.")
      report(:error, node.op.context(node))
    end
  end

  cond_stmts = [:For, :Repeat, :While, :If].map { |cls| tree.all(cls) }.flatten
  cond_stmts.each { |cond_stmt| walk(cond_stmt.cond, cond_stmt) }
end
run() click to toggle source
# File lib/pedant/checks/equality_with_regex.rb, line 57
def run
  # This check will pass by default.
  pass

  # Run this check on the tree from every file.
  @kb[:trees].each { |file, tree| check(file, tree) }
end
walk(node, root) click to toggle source
# File lib/pedant/checks/equality_with_regex.rb, line 34
def walk(node, root)
  # Recursively descend into the right-hand and left-hand sides of each expression.
  if node.is_a? Nasl::Expression
    [:lhs, :rhs].each { |side| walk(node.send(side), root) }

    return unless node.op.is_a?(Nasl::Token)
    return unless ["==", "!="].include?(node.op.body)
    return unless node.rhs.is_a?(Nasl::String)
    str = node.rhs.text
    return unless str.length > 2
    return unless str[0] == "^" and str[-1] == "$"

    fail
    report(:error, "An equality comparison is being made with what appears to be a regex.")
    report(:error, "This might be a typo in the operator.")
    report(:error, node.op.context(node))
  end
end