Class: Lisp::Format::Lexer

Inherits:
Object show all
Defined in:
lib/carat/lisp-format.rb

Overview

Given a format string, this class lexes it and returns directives it finds. This includes gathering parameters and modifiers for the coming directives. The necessary information to create a directive is gathered and then passed to Directives::Factory#build. Error checking is performed, so that incomplete parameters are caught and malformed modifiers are supressed.

Constant Summary collapse

@@errorstates =
{
  :START => [MissingParameterError,
    'format string ended before parameter was found'],
  :CHAR => [IncompleteParameterError,
    'format string ended before character parameter could be read'],
  :INTEGER => [IncompleteParameterError,
    'format string ended before integer parameter could be read'],
}

Instance Method Summary collapse

Constructor Details

#initialize(format) ⇒ Lexer

Create a new Lexer using the given format string format.



229
230
231
232
# File 'lib/carat/lisp-format.rb', line 229

def initialize(format)
  @format = format
  @pos = 0
end

Instance Method Details

#next_token(previous) ⇒ Object

Read the next token, given the previous one in previous, and return it. This may either be a ‘real’ directive created by Directives::Factory#build, or a Literal created in-line. If no more tokens remain, nil is returned.



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/carat/lisp-format.rb', line 238

def next_token(previous)
  if have_more_input
    ch = next_char
    if ch == ?~
      return Directives::Factory.build(params, modifiers, directive,
                                      previous, @pos)
    else
      literal = Directives::Literal.new(ch.chr)
      while have_more_input and (ch = peek_char) != ?~
        literal << next_char.chr
      end
      literal << ch.chr if not have_more_input and ch == ?~
      return [literal, 0]
    end
  else
    return nil
  end
end