Class: LineNumberingProcessor

Inherits:
SexpProcessor
  • Object
show all
Defined in:
lib/sexp_path/line_numbering_processor.rb

Overview

Transforms a Sexp, keeping track of newlines. This uses the internal ruby newline nodes so they must be included in the Sexp to be transformed. If ParseTree is being used, it should be configured to include newlines:

parser = ParseTree.new(true) # true => include_newlines

LineNumberingProcessor.rewrite_file(path) should be used as a short cut if ParseTree is available.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLineNumberingProcessor

Creates a new LineNumberingProcessor.



31
32
33
34
# File 'lib/sexp_path/line_numbering_processor.rb', line 31

def initialize()
  super
  @unsupported.delete :newline
end

Class Method Details

.rewrite_file(path) ⇒ Object

Helper method for generating a Sexp with line numbers from a file at path.

Only available if ParseTree is loaded.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sexp_path/line_numbering_processor.rb', line 15

def self.rewrite_file(path)
  raise 'ParseTree must be installed.' unless Object.const_defined? :ParseTree
  
  code = File.read(path)
  sexp = Sexp.from_array(ParseTree.new(true).parse_tree_for_string(code, path).first)
  processor = LineNumberingProcessor.new
  
  # Fill in the first lines with a value
  sexp.line = 0
  sexp.file = path
  
  # Rewrite the sexp so that everything gets a line number if possible.
  processor.rewrite sexp
end

Instance Method Details

#rewrite(exp) ⇒ Object

Rewrites a Sexp using :newline nodes to fill in line and file information.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sexp_path/line_numbering_processor.rb', line 37

def rewrite exp
  unless exp.nil?
    if exp.sexp_type == :newline
      @line = exp[1]
      @file = exp[2]
    end
    
    exp.file ||= @file
    exp.line ||= @line
  end
  
  super exp
end