Module: Contraction::Parser

Defined in:
lib/parser.rb,
lib/parser/type.rb,
lib/parser/lines.rb

Defined Under Namespace

Classes: ParamLine, ReturnLine, Type, TypedLine

Constant Summary collapse

RETURN_LINE_REGEX =
/^#\s*@return\s+(?<type>\[[^\]]+\])?\s*(?<message>[^{]+)?(?<contract>\{([^}]+)\})?/
PARAM_LINE_REGEX =
/^#\s*@param\s+(?<type>\[[^\]]+\])?\s*(?<name>[^\s]+)\s*(?<message>[^{]+)?(?<contract>\{([^}]+)\})?/

Class Method Summary collapse

Class Method Details

.parse(text, mod, method_name, type) ⇒ Contract

Parses text passed to it for a given method for RDoc @param and @return lines to build contracts. in. contracts/docs apply to correctness at run-time.

Parameters:

  • text (Array, String)

    The text to be parsed.

  • mod (Class, Module)

    The class or module that the method is defined

  • method_name (Symbol, String)

    The name of the method that the

Returns:

  • (Contract)

    A Contract object that can be used to evaluate



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/parser.rb', line 21

def self.parse(text, mod, method_name, type)
  lines = text.is_a?(String) ? text.split(/$/) : text
  results = []
  lines.each do |line|
    line.strip!
    break unless line.start_with? '#'
    break if line.start_with? '##'
    results << parse_line(line.strip)
  end
  results.compact!

  Contract.new(results, mod, method_name, type)
end

.parse_line(line) ⇒ TypedLine

Parse a single line of text for @param and @return statements. type information and contract.

Parameters:

  • line (String)

    The line of text to parse

Returns:

  • (TypedLine)

    An object that represents the parsed line including



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/parser.rb', line 39

def self.parse_line(line)
  if m = line.match(PARAM_LINE_REGEX)
    args = {
      type: m['type'].to_s.gsub(/(\[|\])/, ''),
      name: m['name'],
      message: m['message'],
      contract: (m['contract'] || 'true').gsub(/(^\{)|(\}$)/, '')
    }
    return ParamLine.new(args)
  elsif m = line.match(RETURN_LINE_REGEX)
    args = {
      type: m['type'].to_s.gsub(/(\[|\])/, ''),
      message: m['message'],
      contract: (m['contract'] || 'true').gsub(/(^\{)|(\}$)/, '')
    }
    return ReturnLine.new(args)
  end
end