Class: YARD::Parser::SourceParser

Inherits:
Object
  • Object
show all
Defined in:
lib/yard/parser/source_parser.rb

Overview

Responsible for parsing a source file into the namespace. Parsing also invokes handlers to process the parsed statements and generate any code objects that may be recognized.

Custom Parsers

SourceParser allows custom parsers to be registered and called when a certain filetype is recognized. To register a parser and hook it up to a set of file extensions, call SourceParser.register_parser_type

Constant Summary collapse

SHEBANG_LINE =
/\A\s*#!\S+/
ENCODING_LINE =
%r{\A(?:\s*#*!.*\r?\n)?\s*(?:#+|/\*+|//+).*coding\s*[:=]{1,2}\s*([a-z\d_\-]+)}i
FROZEN_STRING_LINE =
/frozen(-|_)string(-|_)literal:\s+(true|false)/i
DEFAULT_PATH_GLOB =

The default glob of files to be parsed.

Since:

  • 0.9.0

["{lib,app}/**/*.{rb,rbs}", "sig/**/*.rbs", "ext/**/*.{c,cc,cxx,cpp,rb}"]
ENCODING_BYTE_ORDER_MARKS =

Byte order marks for various encodings

Since:

  • 0.7.0

{
  'utf-8' => String.new("\xEF\xBB\xBF"),
  # Not yet supported
  # 'utf-16be' => "\xFE\xFF",
  # 'utf-16le' => "\xFF\xFE",
  # 'utf-32be' => "\x00\x00\xFF\xFE",
  # 'utf-32le' => "\xFF\xFE",
}

Parser Callbacks collapse

Class Attribute Summary collapse

Parser Callbacks collapse

Class Method Summary collapse

Constructor Details

#initialize(parser_type = SourceParser.parser_type, globals = nil) ⇒ SourceParser

Returns a new instance of SourceParser.

Creates a new parser object for code parsing with a specific parser type.

Parameters:

  • parser_type (Symbol) (defaults to: SourceParser.parser_type) —

    the parser type to use

  • globals (OpenStruct) (defaults to: nil) —

    global state to be re-used across separate source files



442
443
444
445
446
447
# File 'lib/yard/parser/source_parser.rb', line 442

def initialize(parser_type = SourceParser.parser_type, globals1 = nil, globals2 = nil)
  globals = [true, false].include?(globals1) ? globals2 : globals1
  @file = '(stdin)'
  @globals = globals || OpenStruct.new
  self.parser_type = parser_type
end

Class Attribute Details

.parser_type ⇒ Symbol

Returns the default parser type (defaults to :ruby).

Returns:

  • (Symbol) —

    the default parser type (defaults to :ruby)



120
121
122
# File 'lib/yard/parser/source_parser.rb', line 120

def parser_type
  @parser_type
end

Instance Attribute Details

#contents ⇒ String (readonly)

Returns the contents of the file to be parsed.

Returns:

  • (String) —

    the contents of the file to be parsed

Since:

  • 0.7.0



435
436
437
# File 'lib/yard/parser/source_parser.rb', line 435

def contents
  @contents
end

#file ⇒ String

Returns the filename being parsed by the parser.

Returns:

  • (String) —

    the filename being parsed by the parser.



422
423
424
# File 'lib/yard/parser/source_parser.rb', line 422

def file
  @file
end

#globals ⇒ OpenStruct (readonly)

Returns an open struct containing arbitrary global state shared between files and handlers.

Returns:

  • (OpenStruct) —

    an open struct containing arbitrary global state shared between files and handlers.

Since:

  • 0.7.0



431
432
433
# File 'lib/yard/parser/source_parser.rb', line 431

def globals
  @globals
end

#parser_type ⇒ Symbol

Returns the parser type associated with the parser instance. This should be set by the constructor.

Returns:

  • (Symbol) —

    the parser type associated with the parser instance. This should be set by the constructor.



426
427
428
# File 'lib/yard/parser/source_parser.rb', line 426

def parser_type
  @parser_type
end

Class Method Details

.after_parse_file {|parser| ... } ⇒ Proc

Registers a callback to be called after an individual file is parsed. The block passed to this method will be called on subsequent parse calls.

To register a callback that is called after the entire list of files is processed, see after_parse_list.

Examples:

Printing the length of each file after it is parsed

SourceParser.after_parse_file do |parser|
  puts "#{parser.file} is #{parser.contents.size} characters"
end
YARD.parse('lib/**/*.rb')
# prints:
"lib/foo.rb is 1240 characters"
"lib/foo_bar.rb is 248 characters"

Yields:

  • (parser) —

    the yielded block is called once after each file that is parsed. This might happen many times for a single codebase.

Yield Parameters:

  • parser (SourceParser) —

    the parser object that parsed the file.

Yield Returns:

  • (void) —

    the return value for the block is ignored.

Returns:

  • (Proc) —

    the yielded block

See Also:

Since:

  • 0.7.0



359
360
361
# File 'lib/yard/parser/source_parser.rb', line 359

def after_parse_file(&block)
  after_parse_file_callbacks << block
end

.after_parse_file_callbacks ⇒ Array<Proc>

Returns the list of callbacks to be called after parsing a file. Should only be used for testing.

Returns:

  • (Array<Proc>) —

    the list of callbacks to be called after parsing a file. Should only be used for testing.

Since:

  • 0.7.0



387
388
389
# File 'lib/yard/parser/source_parser.rb', line 387

def after_parse_file_callbacks
  @after_parse_file_callbacks ||= []
end

.after_parse_list {|files, globals| ... } ⇒ Proc

Registers a callback to be called after a list of files is parsed via parse. The block passed to this method will be called on subsequent parse calls.

Examples:

Printing results after parsing occurs

SourceParser.after_parse_list do
  puts "Finished parsing!"
end
YARD.parse
# Prints "Finished parsing!" after parsing files

Yields:

  • (files, globals) —

    the yielded block is called once before parsing all files

Yield Parameters:

Yield Returns:

  • (void) —

    the return value for the block is ignored.

Returns:

  • (Proc) —

    the yielded block

See Also:

Since:

  • 0.7.0



293
294
295
# File 'lib/yard/parser/source_parser.rb', line 293

def after_parse_list(&block)
  after_parse_list_callbacks << block
end

.after_parse_list_callbacks ⇒ Array<Proc>

Returns the list of callbacks to be called after parsing a list of files. Should only be used for testing.

Returns:

  • (Array<Proc>) —

    the list of callbacks to be called after parsing a list of files. Should only be used for testing.

Since:

  • 0.7.0



373
374
375
# File 'lib/yard/parser/source_parser.rb', line 373

def after_parse_list_callbacks
  @after_parse_list_callbacks ||= []
end

.before_parse_file {|parser| ... } ⇒ Proc

Registers a callback to be called before an individual file is parsed. The block passed to this method will be called on subsequent parse calls.

To register a callback that is called before the entire list of files is processed, see before_parse_list.

Examples:

Installing a simple callback

SourceParser.before_parse_file do |parser|
  puts "I'm parsing #{parser.file}"
end
YARD.parse('lib/**/*.rb')
# prints:
"I'm parsing lib/foo.rb"
"I'm parsing lib/foo_bar.rb"
"I'm parsing lib/last_file.rb"

Cancel parsing of any test_*.rb files

SourceParser.before_parse_file do |parser|
  return false if parser.file =~ /^test_.+\.rb$/
end

Yields:

  • (parser) —

    the yielded block is called once before each file that is parsed. This might happen many times for a single codebase.

Yield Parameters:

Yield Returns:

  • (Boolean) —

    if the block returns false, parsing for the file is cancelled.

Returns:

  • (Proc) —

    the yielded block

See Also:

Since:

  • 0.7.0



330
331
332
# File 'lib/yard/parser/source_parser.rb', line 330

def before_parse_file(&block)
  before_parse_file_callbacks << block
end

.before_parse_file_callbacks ⇒ Array<Proc>

Returns the list of callbacks to be called before parsing a file. Should only be used for testing.

Returns:

  • (Array<Proc>) —

    the list of callbacks to be called before parsing a file. Should only be used for testing.

Since:

  • 0.7.0



380
381
382
# File 'lib/yard/parser/source_parser.rb', line 380

def before_parse_file_callbacks
  @before_parse_file_callbacks ||= []
end

.before_parse_list {|files, globals| ... } ⇒ Proc

Registers a callback to be called before a list of files is parsed via parse. The block passed to this method will be called on subsequent parse calls.

Examples:

Installing a simple callback

SourceParser.before_parse_list do |files, globals|
  puts "Starting to parse..."
end
YARD.parse('lib/**/*.rb')
# prints "Starting to parse..."

Setting global state

SourceParser.before_parse_list do |files, globals|
  globals.method_count = 0
end
SourceParser.after_parse_list do |files, globals|
  puts "Found #{globals.method_count} methods"
end
class MyCountHandler < Handlers::Ruby::Base
  handles :def, :defs
  process { globals.method_count += 1 }
end
YARD.parse
# Prints: "Found 37 methods"

Using a global callback to cancel parsing

SourceParser.before_parse_list do |files, globals|
  return false if files.include?('foo.rb')
end

YARD.parse(['foo.rb', 'bar.rb']) # callback cancels this method
YARD.parse('bar.rb') # parses normally

Yields:

  • (files, globals) —

    the yielded block is called once before parsing all files

Yield Parameters:

Yield Returns:

  • (Boolean) —

    if the block returns false, parsing is cancelled.

Returns:

  • (Proc) —

    the yielded block

See Also:

Since:

  • 0.7.0



269
270
271
# File 'lib/yard/parser/source_parser.rb', line 269

def before_parse_list(&block)
  before_parse_list_callbacks << block
end

.before_parse_list_callbacks ⇒ Array<Proc>

Returns the list of callbacks to be called before parsing a list of files. Should only be used for testing.

Returns:

  • (Array<Proc>) —

    the list of callbacks to be called before parsing a list of files. Should only be used for testing.

Since:

  • 0.7.0



366
367
368
# File 'lib/yard/parser/source_parser.rb', line 366

def before_parse_list_callbacks
  @before_parse_list_callbacks ||= []
end

.parse(paths = DEFAULT_PATH_GLOB, excluded = [], level = log.level) ⇒ void

This method returns an undefined value.

Parses a path or set of paths

Parameters:

  • paths (String, Array<String>) (defaults to: DEFAULT_PATH_GLOB) —

    a path, glob, or list of paths to parse

  • excluded (Array<String, Regexp>) (defaults to: []) —

    a list of excluded path matchers

  • level (Fixnum) (defaults to: log.level) —

    the logger level to use during parsing. See Logger



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/yard/parser/source_parser.rb', line 134

def parse(paths = DEFAULT_PATH_GLOB, excluded = [], level = log.level)
  log.debug("Parsing #{paths.inspect} with `#{parser_type}` parser")
  excluded = excluded.map do |path|
    case path
    when Regexp; path
    else Regexp.new(path.to_s, Regexp::IGNORECASE)
    end
  end
  files = [paths].flatten.
    map {|p| File.directory?(p) ? "#{p}/**/*.{rb,rbs,c,cc,cxx,cpp}" : p }.
    map {|p| p.include?("*") ? Dir[p].sort_by {|d| [d.length, d] } : p }.flatten.
    reject {|p| !File.file?(p) || excluded.any? {|re| p =~ re } }.
    map {|p| p.encoding == Encoding.default_external ? p : p.dup.force_encoding(Encoding.default_external) }

  log.enter_level(level) do
    parse_in_order(*files.uniq)
  end
end

.parse_string(content, ptype = parser_type) ⇒ Object

Parses a string content

Parameters:

  • content (String) —

    the block of code to parse

  • ptype (Symbol) (defaults to: parser_type) —

    the parser type to use. See parser_type.

Returns:

  • the parser object that was used to parse content



158
159
160
# File 'lib/yard/parser/source_parser.rb', line 158

def parse_string(content, ptype = parser_type)
  new(ptype).parse(StringIO.new(content))
end

.parser_type_extensions=(value) ⇒ Object



199
# File 'lib/yard/parser/source_parser.rb', line 199

def parser_type_extensions=(value) @@parser_type_extensions = value end

.parser_type_for_extension(extension) ⇒ Symbol

Finds a parser type that is registered for the extension. If no type is found, the default Ruby type is returned.

Returns:

  • (Symbol) —

    the parser type to be used for the extension

Since:

  • 0.5.6



206
207
208
209
210
211
# File 'lib/yard/parser/source_parser.rb', line 206

def parser_type_for_extension(extension)
  type = parser_type_extensions.find do |_t, exts|
    [exts].flatten.any? {|ext| ext === extension }
  end
  validated_parser_type(type ? type.first : :ruby)
end

.parser_types=(value) ⇒ Object



193
# File 'lib/yard/parser/source_parser.rb', line 193

def parser_types=(value) @@parser_types = value end

.register_parser_type(type, parser_klass, extensions = nil) ⇒ void

This method returns an undefined value.

Registers a new parser type.

Examples:

Registering a parser for "java" files

SourceParser.register_parser_type :java, JavaParser, 'java'

Parameters:

  • type (Symbol) —

    a symbolic name for the parser type

  • parser_klass (Base) —

    a class that implements parsing and tokenization

  • extensions (Array<String>, String, Regexp) (defaults to: nil) —

    a list of extensions or a regex to match against the file extension

See Also:



181
182
183
184
185
186
187
# File 'lib/yard/parser/source_parser.rb', line 181

def register_parser_type(type, parser_klass, extensions = nil)
  unless Base > parser_klass
    raise ArgumentError, "expecting parser_klass to be a subclass of YARD::Parser::Base"
  end
  parser_type_extensions[type.to_sym] = extensions if extensions
  parser_types[type.to_sym] = parser_klass
end

.tokenize(content, ptype = parser_type) ⇒ Array

Tokenizes but does not parse the block of code

Parameters:

  • content (String) —

    the block of code to tokenize

  • ptype (Symbol) (defaults to: parser_type) —

    the parser type to use. See parser_type.

Returns:

  • (Array) —

    a list of tokens



167
168
169
# File 'lib/yard/parser/source_parser.rb', line 167

def tokenize(content, ptype = parser_type)
  new(ptype).tokenize(content)
end

Instance Method Details

#parse(content = __FILE__) ⇒ Object?

The main parser method. This should not be called directly. Instead, use the class methods parse and parse_string.

Parameters:

  • content (String, #read, Object) (defaults to: __FILE__) —

    the source file to parse

Returns:

  • (Object, nil) —

    the parser object used to parse the source



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/yard/parser/source_parser.rb', line 454

def parse(content = __FILE__)
  case content
  when String
    @file = File.cleanpath(content)
    content = convert_encoding(String.new(File.read_binary(file)))
    checksum = Registry.checksum_for(content)
    return if Registry.checksums[file] == checksum

    if Registry.checksums.key?(file)
      log.info "File '#{file}' was modified, re-processing..."
    end
    Registry.checksums[@file] = checksum
    self.parser_type = parser_type_for_filename(file)
  else
    content = content.read if content.respond_to? :read
  end

  @contents = content
  @parser = parser_class.new(content, file)

  self.class.before_parse_file_callbacks.each do |cb|
    return @parser if cb.call(self) == false
  end

  @parser.parse
  post_process

  self.class.after_parse_file_callbacks.each do |cb|
    cb.call(self)
  end

  @parser
rescue ArgumentError, NotImplementedError => e
  log.warn("Cannot parse `#{file}': #{e.message}")
  log.backtrace(e, :warn)
rescue ParserSyntaxError => e
  log.warn(e.message.capitalize)
  log.backtrace(e, :warn)
end

#tokenize(content) ⇒ Array

Tokenizes but does not parse the block of code using the current #parser_type

Parameters:

  • content (String) —

    the block of code to tokenize

Returns:

  • (Array) —

    a list of tokens



498
499
500
501
# File 'lib/yard/parser/source_parser.rb', line 498

def tokenize(content)
  @parser = parser_class.new(content, file)
  @parser.tokenize
end