Class: XMP2Assert::Parser

Inherits:
Ripper
  • Object
show all
Defined in:
lib/xmp2assert/parser.rb

Overview

This is a Ruby parser. Generates ASTs from the given program.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj, file = nil, line = nil) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • obj (Quasifile, URI, Pathname, String, File, IO)

    a file-ish.

  • file (String) (defaults to: nil)

    path of the file (optional).

  • line (Integer) (defaults to: nil)

    line offset (optional).

Raises:

  • (SyntaxError)

    failed to parse the program.



38
39
40
41
42
43
44
# File 'lib/xmp2assert/parser.rb', line 38

def initialize obj, file = nil, line = nil
  @qfile = XMP2Assert::Quasifile.new obj, file, line
  super @qfile.read, *locations
  @tokens = []
  @sexp = parse
  @tokens.sort!
end

Instance Attribute Details

#sexpArray (readonly)

Returns constructed s-expression.

Returns:

  • (Array)

    constructed s-expression.



34
35
36
# File 'lib/xmp2assert/parser.rb', line 34

def sexp
  @sexp
end

#tokensArray<Token> (readonly)

Returns program, split into tokens.

Returns:

  • (Array<Token>)

    program, split into tokens.



33
34
35
# File 'lib/xmp2assert/parser.rb', line 33

def tokens
  @tokens
end

Instance Method Details

#locationsString, Integer

Returns the program's file name and line offset.

Returns:

  • (String, Integer)

    the program's file name and line offset.



47
48
49
# File 'lib/xmp2assert/parser.rb', line 47

def locations
  return @qfile.__FILE__, @qfile.__LINE__
end

#same_line_as(tok) ⇒ Array

Find tokens that are in the same line as the argument.

[ 1, # => 1
  2, # => 2
]    # => [1, 2]

It will return [(:sp ' ') (:int 2) (:'=>' "2")] for (:'=>' "2").

Parameters:

  • tok (Token)

    a token to look at.

Returns:

  • (Array)

    tokens of the same line as the argument.



63
64
65
66
# File 'lib/xmp2assert/parser.rb', line 63

def same_line_as tok
  f, l = tok.__FILE__, tok.__LINE__
  return @tokens.select {|i| i.__FILE__ == f }.select {|i| i.__LINE__ == l }
end