Commit 797d3fcc authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Add line numbers to EsprimaParser results.

parent dfe3ea6e
Loading
Loading
Loading
Loading
+15 −2
Original line number Diff line number Diff line
@@ -16,7 +16,14 @@ module JsDuck
      @v8.load(esprima)
    end

    # Input must be a String.
    # Parses JavaScript source code and returns array of hashes like this:
    #
    #     {
    #         :comment => "The contents of the comment",
    #         :code => {...AST data structure for code following the comment...},
    #         :linenr => 12,  // Beginning with 1
    #     }
    #
    def parse(input)
      @v8['js'] = @input = input

@@ -71,11 +78,17 @@ module JsDuck
      @ast["comments"].map do |comment|
        {
          :comment => comment["value"],
          :code => stuff_after(comment)
          :code => stuff_after(comment),
          :linenr => line_number(comment["range"][0]),
        }
      end
    end

    # Given index inside input string, returns the corresponding line number
    def line_number(index)
      @input[0...index].count("\n") + 1
    end

    # Sees if there is some code following the comment.
    # Returns the code found.  But if the comment is instead
    # followed by another comment, returns nil.
+19 −0
Original line number Diff line number Diff line
@@ -6,6 +6,25 @@ describe JsDuck::EsprimaParser do
    JsDuck::EsprimaParser.instance.parse(input)
  end

  describe "parsing two comments" do
    before do
      @docs = parse(<<-EOS)
        /* Hello world
        */

        // Another
      EOS
    end

    it "detects 1-based line number of comment on first line" do
      @docs[0][:linenr].should == 1
    end

    it "detects line number of second comment on 4th line" do
      @docs[1][:linenr].should == 4
    end
  end

  describe "parsing comment after function" do
    before do
      @docs = parse(<<-EOS)