Sha256: a1835d12eb71817bf689d570978a8d4c4c4ea4332a7e3ff3f47ef58a82d588e8

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

require_relative 'ns_macro_processor/processor_error'
require_relative 'ns_macro_processor/syntax_error'
require_relative 'ns_macro_processor/tokens'

module NsMacroProcessor

  class Processor

    def initialize(params)
      @params = params
    end

    def parse(text)
      @tokens = Tokens.new(text)
      @tokens.advance
      result = words
      expect(Tokens::EOF)
      result
    end

    private

    def words
      result = []
      while @tokens.peek != Tokens::EOF
        result << word
      end
      result.join
    end

    def word
      result = @tokens.peek
      @tokens.advance
      if result == '~' and accept('{')
        @tokens.push_back(macro)
        result = word
      end
      result
    end

    def macro
      args = []
      loop do
        args << word
        break if @tokens.peek == '}' || @tokens.peek == Tokens::EOF
      end
      expect('}')
      execute(args.join.split(' '))
    end

    def execute(args)
      if args[0] == 'include'
        return lookup(:filestore).contents_of(args[1])
      else
        return lookup(args[0])
      end
    end

    def lookup(field_name)
      value = @params[field_name] || @params[field_name.to_sym]
      raise ProcessorError.new(field_name) unless value
      value
    end

    def accept(s)
      if (@tokens.peek == s)
        @tokens.advance
        true
      else
        false
      end
    end

    def expect(s)
      return true if accept(s)
      raise SyntaxError.new(s, @tokens.peek)
      false
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ns-macro-processor-0.0.2 lib/ns_macro_processor.rb