class TopDown::CharReader

Overview

Base class of a Parser.

It composed from a #source and can read or peek characters taking in account a complete Location on the source.

Direct Known Subclasses

Defined in:

char_reader.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(source : String) #

Creates a new CharReader (or Parser), initialized to read the source.


[View source]

Instance Method Detail

def each_char(& : Char -> ) #

Iterates over each source character.

#location is incremented between each character.


[View source]
def location : Location #

Returns the current cursor location.

The location can be used later to raise an error at that point.

loc = self.location
parse('(')
exp = parse!(:expression)
parse!(')', error: "Unterminated parenthesis expression", at: loc)
exp

[View source]
def location=(location : Location) #

Move the cursor to the new location.

The location should be well formed, otherwise error display won't be right. It is recommended to always use a location got by self.location.

This methods is used to backtrack the parser. However, prefer using Parser.union, Parser.maybe, and Parser.repeat over manual backtracks.


[View source]
def next_char : Char #

Returns the next character to parse, and increments the cursor #location.


[View source]
def peek_char #

Returns the next character to parse, without incrementing the cursor #location.

This method is currently the only way to look ahead during the parsing. It allow for instance:

parse("if") do
  break Fail.new if peek_char.alphanumeric?
  Token.new(:if)
end
# as an equivalent to:
parse(/if\b/) { Token.new(:if) }

[View source]
def previous_assci_char? : Char | Nil #

[View source]
def source : String #

[View source]
def source=(source : String) #

Modifies the source and reset the cursor #location to zero.


[View source]