Class: Pedant::CheckNonsenseComparison

Inherits:
Check
  • Object
show all
Defined in:
lib/pedant/checks/nonsense_comparison.rb

Instance Attribute Summary

Attributes inherited from Check

#result

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Check

all, depends, #fail, #fatal, friendly_name, inherited, #initialize, initialize!, list, #pass, provides, ready?, #report, run_checks_in_dependency_order, #skip, #warn

Constructor Details

This class inherits a constructor from Pedant::Check

Class Method Details

.requiresObject



31
32
33
# File 'lib/pedant/checks/nonsense_comparison.rb', line 31

def self.requires
  super + [:trees]
end

Instance Method Details

#check(file, tree) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/pedant/checks/nonsense_comparison.rb', line 35

def check(file, tree)
  literals = Set.new [
    Nasl::Array,
    Nasl::List,
    Nasl::Integer,
    Nasl::String,
    Nasl::Ip
  ]

  comparisons = Set.new [ "==", "!=", "=~", "!~", "><", ">!<", "<", ">", "<=", ">=" ]

  # isnull() with a literal (never FALSE).
  tree.all(:Call).each do |call|
    next if call.name.ident.name != "isnull"
    next if call.name.indexes != []
    next if call.args.length != 1
    next if not literals.include? call.args.first.expr.class
    fail
    report(:error, "isnull() is called with a literal, which can never be FALSE.")
    report(:error, call.args.first.context(call))
  end

  # Comparing a literal to another literal (either TRUE or FALSE, but pointless).
  tree.all(:Expression).each do |expr|
    next if not literals.include? expr.lhs.class
    next if not literals.include? expr.rhs.class
    next if not comparisons.include? expr.op.to_s
    fail
    report(:error, "Comparing two literals is always TRUE or FALSE.")
    report(:error, expr.op.context(expr))
  end

  # Comparing something against itself.
  tree.all(:Expression).each do |expr|
    next if not comparisons.include? expr.op.to_s
    next if not expr.lhs.is_a? Nasl::Lvalue
    next if not expr.rhs.is_a? Nasl::Lvalue
    # Compare the XML representations of the two Lvalues.
    # Handles integer keys nicely, so these two are the same: a[0x01] == a[1]
    xmls = [:lhs, :rhs].map do |side|
      expr.send(side).to_xml(Builder::XmlMarkup.new)
    end
    next if xmls[0] != xmls[1]
    fail
    report(:error, "Comparing two identical Lvalues. This will always be TRUE.")
    report(:error, expr.op.context(expr))
  end
end

#runObject



84
85
86
87
88
89
90
# File 'lib/pedant/checks/nonsense_comparison.rb', line 84

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