1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
11 # Simple base for hand-made parsers of all kinds
16 # Basic facilities for common parser operations on String sources
18 # Source document to parse
19 protected var src
: String
21 # Length of the source document
22 protected var len
: Int is noinit
24 # Current position in `src`
27 # Position at which current line started
28 protected var line_start
= 0
30 # Current line in `src`
31 protected var line
= 1
33 # Offset in the current line
34 protected fun line_offset
: Int do return pos
- line_start
+ 1
40 # Gives the current location in the `src`
41 fun current_location
: Location do return new Location(line
, line_offset
)
43 # Advances in `src` until a non-whitespace character is encountered
44 protected fun ignore_whitespaces
do
47 if p
>= srclen
then return
49 while c
.is_whitespace
do
51 if p
>= srclen
then break
62 # Reads characters until pattern `s` is found
63 protected fun ignore_until
(s
: String): Int do
64 if s
.length
== 0 then return _pos
67 if p
>= srclen
then return -1
86 if relpos
>= srclen
then
90 if src
[relpos
] != i
then
104 # Ignores any printable character until a whitespace is encountered
105 protected fun ignore_until_whitespace
: Int do
106 while src
.length
> pos
and not src
[pos
].is_whitespace
do pos
+= 1
110 # Returns the current location as a `Location` object
111 protected fun hot_location
: Location do return new Location(line
, line_offset
)
113 # Is `pos` at the end of the source?
114 protected fun eof
: Bool do return pos
>= src
.length
117 # Information about the location of an entity in a source document
121 # Line in which the element is described
123 # Offset in the line at which the element is positioned
126 redef fun to_s
do return "line {line}, position {offset}"