Class: Kalc::Grammar

Inherits:
Parslet::Parser
  • Object
show all
Defined in:
lib/kalc/grammar.rb

Overview

Started with github.com/postmodern/cparser code which is based on www.lysator.liu.se/c/ANSI-C-grammar-y.html and worked from there

The second link really helped when it came to functions

Class Method Summary collapse

Class Method Details

.operators(operators = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/kalc/grammar.rb', line 38

def self.operators(operators = {})
  trailing_chars = Hash.new { |hash, symbol| hash[symbol] = [] }

  operators.each_value do |symbol|
    operators.each_value do |op|
      if op[0, symbol.length] == symbol
        char = op[symbol.length, 1]

        unless char.nil? || char.empty?
          trailing_chars[symbol] << char
        end
      end
    end
  end

  operators.each do |name, symbol|
    trailing = trailing_chars[symbol]

    if trailing.empty?
      rule(name) { str(symbol).as(:operator) >> spaces? }
    else
      pattern = "[#{Regexp.escape(trailing.join)}]"

      rule(name) {
        (str(symbol) >> match(pattern).absnt?).as(:operator) >> spaces?
      }
    end
  end
end

.symbols(symbols) ⇒ Object



24
25
26
27
28
# File 'lib/kalc/grammar.rb', line 24

def self.symbols(symbols)
  symbols.each do |name, symbol|
    rule(name) { str(symbol) >> spaces? }
  end
end