1 define: #Lexer &parents: {StreamProcessor}
2 &slots: {#inputBuffer -> ExtensibleArray new.
3 #outputBuffer -> ExtensibleArray new.
4 "A backing buffer of tokens for undo functionality."
5 #lineNumber -> 1 "The current line number."}.
6 "The lexer takes an input character Stream and divides it up into Tokens,
7 using a buffer as necessary to hold the tokenized contents.
8 Also, debugging information is stored for now in terms of the line number that
9 the current stream position has reached."
10 Lexer traits define: #WordTerminatingTokens -> '()[]{}@,.|!#$`"\'%'.
12 l@(Lexer traits) on: stream
13 "Target the lexer to the particular stream and initialize it."
15 l `>> [resend. reset. ]
18 l@(Lexer traits) reset
20 l inputBuffer := l inputBuffer new.
21 l outputBuffer := l outputBuffer new.
25 l@(Lexer traits) showTokensFrom: src
27 (l newOn: src) do: [| :x | inform: x printString].
30 l@(Lexer traits) isEndOfLine: char [char == $\n].
31 l@(Lexer traits) isEscape: char [char == $\\].
33 l@(Lexer traits) isAtEnd
34 "The lexer has reached its end when the stream is exhausted and the buffer is
37 l outputBuffer isEmpty /\ [l hasMoreCharacters not]
40 l@(Lexer traits) hasMoreCharacters
41 "Answers whether more characters are immediately available."
43 "It is important not to query the source stream, unless the input buffer is
45 l inputBuffer isEmpty not \/ [l source isAtEnd not]
48 Lexer traits define: #Error &parents: {DescriptiveError}
49 &slots: {#lineNumber -> 0 "The line number on which the error was detected."}.
50 "An error that occurred in parsing, always requiring a description."
52 l@(Lexer traits) error: description
54 (l Error newDescription:
55 'Line ' ; l lineNumber printString ; ': ' ; description)
56 `>> [lineNumber := l lineNumber. signal]
59 l@(Lexer traits) nextCharacter
60 "To get the next character, either pull one from the buffer or read from the
61 stream of characters. Raise an error if this is used at the end, and advance
62 the line number if a new-line is reached."
64 c := l inputBuffer isEmpty
67 ifTrue: [l error: 'Unexpected end of stream'].
69 ifFalse: [l inputBuffer removeLast].
70 (l isEndOfLine: c) ifTrue: [l lineNumber += 1].
74 l@(Lexer traits) undoCharacter: c
75 "Put the character back into the buffer, and decrement the line number if it's
78 (l isEndOfLine: c) ifTrue: [l lineNumber -= 1].
79 l inputBuffer addLast: c
82 l@(Lexer traits) peekCharacter
83 "Grab the next character, but leave it in the buffer, so the position is not
87 ifTrue: [l undoCharacter: l nextCharacter]
88 ifFalse: [l inputBuffer last]
91 l@(Lexer traits) peekCharacterForwardBy: n
94 ifTrue: [l undoCharacter: l nextCharacter]
95 ifFalse: [l inputBuffer last]
98 l@(Lexer traits) readInteger: radix
99 "The general method for building integers from the raw characters, with a
100 radix (number of digits) parameter. Grab all following digits for the radix,
101 multiplying the accumulator by the radix and adding the numeric equivalent
105 [l hasMoreCharacters /\ [(l peekCharacter isDigit: radix) \/ [l peekCharacter == $_]]] whileTrue:
107 ((c := l nextCharacter) toDigit: radix) ifNotNilDo:
108 [| :digit | number := number * radix + digit]].
112 l@(Lexer traits) readMantissa: radix
113 "Build a floating-point number's fractional part."
117 [l hasMoreCharacters /\ [(l peekCharacter isDigit: radix) \/ [l peekCharacter == $_]]] whileTrue:
119 ((c := l nextCharacter) toDigit: radix) ifNotNilDo:
121 number := number * radix + digit.
123 (number as: Float) / (place as: Float)
126 l@(Lexer traits) readExponent: radix
127 "Build a floating-point number's exponent as an integer."
129 (c := l nextCharacter) == $-
130 ifTrue: [(l readInteger: radix) negated]
132 [c == $+ ifFalse: [l undoCharacter: c]. l readInteger: radix]
135 l@(Lexer traits) newLiteralFor: obj
136 [tokens LiteralToken for: obj].
138 "l@(Lexer traits) newLiteralFor: a@(ByteArray traits)
141 ifTrue: [TODO: 'intern empty array/bytearray/string']
145 l@(Lexer traits) readNumber
146 "The overall routine for building numbers."
147 [| number isNegative radix c |
150 (c := l nextCharacter) == $-
151 ifTrue: [isNegative := True]
152 ifFalse: [c == $+ ifFalse: [l undoCharacter: c]].
153 "Now read in all the continuous string of digits possible as an integer."
154 number := l readInteger: radix.
155 "Reaching the end of the lexing stream just finalizes the process."
156 l hasMoreCharacters ifTrue:
157 ["Conditionalize on the next character: it may set up a radix or a decimal."
158 (c := l nextCharacter) == $r \/ [c == $R] ifTrue:
159 [((radix := number) between: 2 and: 36) ifFalse:
160 [l error: 'Number radix must be between 2 and 36.'].
161 number := l readInteger: radix.
163 ifTrue: [c := l nextCharacter]
165 [^ (l newLiteralFor: (isNegative ifTrue: [number negated] ifFalse: [number]))]].
166 c == $. /\ [l hasMoreCharacters] /\ [l peekCharacter isDigit: radix] ifTrue:
167 [number := (number as: Float) + (l readMantissa: radix).
169 ifTrue: [c := l nextCharacter]
171 [^ (l newLiteralFor: (isNegative ifTrue: [number negated] ifFalse: [number]))]].
174 [number := (number as: Float) * ((radix as: Float) raisedTo: (l readExponent: 10))]
176 [l undoCharacter: c]].
177 l newLiteralFor: (isNegative ifTrue: [number negated] ifFalse: [number])
180 l@(Lexer traits) readEscapedCharacter
181 "Language support for character escapes. This should be called at the point
182 after the initial escape is seen, whether as a character or part of a string."
184 (c := l nextCharacter) caseOf: {
196 [((l nextCharacter toDigit: 16) ifNil:
197 [l error: 'Unexpected numeric-escape Character syntax. Expected $\\xNN']) * 16
198 + ((l nextCharacter toDigit: 16) ifNil:
199 [l error: 'Unexpected numeric-escape Character syntax. Expected $\\xNN'])
200 as: ASCIIString Character]
204 l@(Lexer traits) characterFor: c
205 [(l isEscape: c) ifTrue: [l readEscapedCharacter] ifFalse: [c]].
207 l@(Lexer traits) nextSegmentUntil: terminator
210 [(c := l nextCharacter) == terminator]
212 [result nextPut: (l characterFor: c)]] writingAs: ''
215 l@(Lexer traits) readString
216 "Build a string until the next single-quote character is encountered.
217 Escaping is accounted for."
219 l newLiteralFor: (l nextSegmentUntil: $\')
222 l@(Lexer traits) read: t@(tokens Comment traits)
223 "Build a comment string until the next double-quote character is encountered.
224 Escaping is accounted for."
226 t for: (l nextSegmentUntil: $\")
229 l@(Lexer traits) nextWordCharactersInto: s@(WriteStream traits)
232 /\ [(c := l peekCharacter) isWhitespace not]
233 /\ [(l WordTerminatingTokens includes: c) not]]
234 whileTrue: [s nextPut: l nextCharacter]
237 l@(Lexer traits) read: type@(tokens Selector traits)
238 "Read a selector symbol into a token."
242 l hasMoreCharacters /\ [l peekCharacter isDigit] ifFalse:
243 [l nextWordCharactersInto: result]] writingAs: '') isEmpty
245 ifFalse: [type for: result]
248 l@(Lexer traits) readLiteralPastHash
249 "This handles the literal brace array syntaxes as well as literal symbols."
252 /\ ['({[\'#' includes: l peekCharacter]
254 [l nextCharacter caseOf: {
255 $\( -> [tokens BeginPattern].
256 $\{ -> [tokens BeginLiteralArray].
257 $\[ -> [tokens BeginLiteralBlock].
258 $\' -> [l newLiteralFor:
260 [(c := l nextCharacter) == $\']
262 [result nextPut: (l characterFor: c)]]
263 writingAs: '') intern].
264 $# -> [l nextCharacter = $\(
265 ifTrue: [tokens BeginLiteralParenthesis]
266 ifFalse: [l error: 'Expected ( after ##']]
270 (#(l nextWordCharactersInto: _) `er writingAs: '') intern]
273 l@(Lexer traits) readCharacter
274 "Read in a single character into a token or an escaped one."
276 l newLiteralFor: (l characterFor: l nextCharacter)
279 l@(Lexer traits) read: w@(tokens Whitespace traits)
280 "A way to preserve the whitespace in the original text. Unused by default."
284 [c := l nextCharacter.
287 /\ [(l isEndOfLine: c) not]]
288 whileTrue: [result nextPut: c]] writingAs: ''.
293 l@(Lexer traits) skipWhitespace
295 l hasMoreCharacters ifTrue:
296 [[c := l nextCharacter.
299 /\ [(l isEndOfLine: c) not]]
304 l@(Lexer traits) readToken
305 "The overall handler for tokenization, this conditionalizes on the various
306 initializing characters to build the various token objects."
307 "TODO: place these dispatch tables in persistent places, much like a Lisp
310 "Consume/discard whitespace first."
314 [(c := l nextCharacter) caseOf: {
315 $\' -> [l readString].
316 $\" -> [l read: tokens Comment].
317 $$ -> [l readCharacter].
318 $# -> [l readLiteralPastHash].
319 $( -> [tokens BeginParenthesis].
320 $) -> [tokens EndParenthesis].
321 ${ -> [tokens BeginArray].
322 $} -> [tokens EndArray].
323 $[ -> [tokens BeginBlock].
324 $] -> [tokens EndBlock].
326 $. -> [tokens EndStatement].
327 $, -> [tokens Comma].
328 $\| -> [tokens BeginVariables].
330 $` -> [(l read: tokens MacroSelector) ifNil: [tokens Quote]].
331 $% -> [(l read: tokens DeferredSelector) ifNil: [tokens Eventually]].
332 $\n -> [tokens EndLine]
334 [c isDigit \/ [c == $+ \/ [c == $-] /\ [l peekCharacter isDigit]]
335 ifTrue: [l undoCharacter: c. l readNumber]
336 ifFalse: [l undoCharacter: c.
337 (l read: tokens Selector)
338 ifNil: [l error: 'Message selector must not be empty.']]]]
339 ifFalse: [tokens EndStream]
342 l@(Lexer traits) next
344 l outputBuffer isEmpty
345 ifTrue: [l readToken]
346 ifFalse: [l outputBuffer removeFirst]
349 l@(Lexer traits) peek
351 l outputBuffer isEmpty
352 ifTrue: [l outputBuffer addLast: l readToken].
356 l@(Lexer traits) peek: n
358 [(l outputBuffer includesKey: n) not]
359 whileTrue: [l outputBuffer addLast: l readToken].
360 l outputBuffer first: n
363 l@(Lexer traits) peekForwardBy: n
365 [(l outputBuffer includesKey: n) not]
366 whileTrue: [l outputBuffer addLast: l readToken].
367 l outputBuffer at: n ifAbsent: [l error: 'Could not find token forward by: ' ; n printString]
370 l@(Lexer traits) undoToken: token
372 l outputBuffer addFirst: token
375 _@(Lexer traits) undoToken: t@(tokens EndStream traits)
376 "Avoid placing EndStream tokens in the output buffer."
379 t@(tokens Token traits) readFrom: s
381 ((next := (Lexer newOn: s reader) next) is: t)
383 ifFalse: [error: 'The source did not parse into ' ; t printName asAn ; '.']