Sha256: 8a31c03009278cb9fb0283706000f5b400db01298163a814445e2420fd283865

Contents?: true

Size: 1.13 KB

Versions: 23

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module SlimLint::Filters
  # Traverses a Temple S-expression (that has already been converted to
  # {SlimLint::Sexp} instances) and annotates them with line numbers.
  #
  # This is a hack that allows us to access line information directly from the
  # S-expressions, which makes a lot of other tasks easier.
  class InjectLineNumbers < Temple::Filter
    # {Sexp} representing a newline.
    NEWLINE_SEXP = SlimLint::Sexp.new([:newline])

    # Annotates the given {SlimLint::Sexp} with line number information.
    #
    # @param sexp [SlimLint::Sexp]
    # @return [SlimLint::Sexp]
    def call(sexp)
      @line_number = 1
      traverse(sexp)
      sexp
    end

    private

    # Traverses an {Sexp}, annotating it with line numbers.
    #
    # @param sexp [SlimLint::Sexp]
    def traverse(sexp)
      sexp.line = @line_number

      case sexp
      when SlimLint::Atom
        @line_number += sexp.strip.count("\n") if sexp.respond_to?(:count)
      when NEWLINE_SEXP
        @line_number += 1
      else
        sexp.each do |nested_sexp|
          traverse(nested_sexp)
        end
      end
    end
  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
slim_lint-0.31.1 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.31.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.30.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.29.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.28.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.27.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.26.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.25.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.24.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.23.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.22.1 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.22.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.21.1 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.21.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.20.2 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.20.1 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.20.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.19.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.18.0 lib/slim_lint/filters/inject_line_numbers.rb
slim_lint-0.17.1 lib/slim_lint/filters/inject_line_numbers.rb