Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Role of the lexical analyser and input buffering

Role of the lexical analyser (scanner) is to read source characters, group them into tokens using patterns, and present a stream of tokens to the parser while using input-buffering techniques (sentinels, two-buffer scheme) to make scanning efficient and correct.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Compiler engineers and tool builders use the lexical analyser (scanner) in the compiler front end to convert raw source text into a stream of tokens that the parser can use. Correct, fast scanning reduces compiler latency, avoids parsing mistakes at token boundaries, and simplifies later phases (syntax analysis, semantic analysis, code generation).

Key ideas

  • Token — a pair (token-name, attribute-value). The token-name is a symbolic category such as IDENTIFIER, NUMBER, PLUS. The attribute-value carries extra information (e.g., the exact lexeme or numeric value). Formal university-style statement: "A token is an abstraction that represents a syntactic category; formally, the scanner maps lexeme L to a token t = (name, attr) if L matches the pattern associated with name." Assumption: token patterns are regular languages.

  • Pattern — a rule (usually a regular expression) that specifies the set of lexemes belonging to a token. Example pattern for identifier: [A-Za-z_][A-Za-z0-9_]*.

  • Scanner (lexical analyser) — a program or module that implements the mapping from the source character stream to a token stream. Responsibilities: skip whitespace and comments (unless significant), implement maximal-munch, return tokens with attributes, report lexical errors.

  • Maximal-munch (longest-match) rule — exact statement: "Given the current unread suffix of the input, the scanner selects the longest prefix that matches some token pattern. If multiple token patterns match the same longest prefix, a fixed precedence (language or scanner-specified) selects the token." Assumptions: patterns are regular and the input alphabet is defined. This rule avoids premature tokenization (e.g., == vs =).

  • Lookahead — the scanner often needs to examine one or more upcoming characters to decide which token is present. Single lookahead means peeking one character beyond the current lexeme; retracting may be needed if lookahead was read but not part of the lexeme.

  • Retract (or unget) — operation that moves the current input pointer back by one (or more) characters so that characters not part of the token are available to the next token scan. If the scanner uses buffering, retract must be efficient and correct across buffer boundaries.

  • Input buffering — techniques to read characters from the source file into memory buffers so that get-character and retract operations are efficient and the scanner can handle arbitrarily long inputs without per-character I/O overhead.

  • Two-buffer (sentinel) scheme — exact definition: two fixed-size buffers are used (left and right halves), each filled from the input file. Each buffer is terminated by a sentinel character (special EOF marker) so that getChar can avoid checking end-of-buffer on every read. A described algorithm is below. Assumptions: the file supports sequential reads and the buffer size is at least 2 (practical sizes: 4 KB or 8 KB).

  • Buffer pointers — typically lexemeBegin (start of current lexeme) and forward (scanner read pointer). The scanner advances forward to collect characters; when a token is recognized, lexemeBegin is set to forward for the next token.

  • Lexical errors — characters or sequences that do not match any pattern. Scanner must report and recover (skip, substitute token, or abort) according to language policy.

Diagram to draw (for exam):

  • Draw two adjacent rectangles of equal width, label them Buffer A and Buffer B. Inside each, draw character cells filled with input characters. At the end of each buffer cell sequence draw a special box labelled 'EOF sentinel' (\0 or special flag). Draw two arrows: one arrow labelled lexemeBegin pointing to some position in Buffer A, another arrow labelled forward moving toward the right possibly into Buffer B. If forward points to the sentinel, show re-fill of the other buffer and movement of forward into it.

Pseudocode, exactly as professors expect, is given in Worked examples section.

Formulas

(For a programming topic we list syntax and function prototypes to remember.)

#define BUFSIZE 4096 — typical buffer size in bytes; choose power of two for performance.

int getChar(void) — returns next character (as int), returns EOF sentinel when file ends.

void retract(void) — move forward pointer one position back (used when a lookahead char does not belong to current token).

int getNextToken(void) — high-level scanner routine that returns the next token code; uses getChar, retract and pattern-matching DFA.

char buffer[2][BUFSIZE+1]; — two-buffer array; extra 1 for sentinel.

void fillBuffer(int b) — loads next chunk of input into buffer b and places sentinel at end.

Worked examples

Example 1 — simple token stream trace (no buffer boundary crossing) Input: int count = 007; (assume newline after semicolon) Assumptions: whitespace skipped, number pattern = [0-9]+. Initial: lexemeBegin = forward = start of buffer. Steps:

  1. getChar returns i, forward advances. Start building lexeme.
  2. Read n, read t. After reading t next getChar returns space. The DFA for identifier matches int as an identifier but we then check if int is a keyword. According to maximal-munch, the longest match is int. So token returned: KEYWORD(int) (or token-name INT_KEYWORD depending on language). On return, lexemeBegin set to char after space.
  3. Skip whitespace until c. Read count by reading letters and digits; next getChar returns space, so emit IDENTIFIER('count').
  4. Skip whitespace, read = then space => emit ASSIGN token.
  5. Skip whitespace, read 0, 0, 7. After reading 7, the next getChar reads ;, which does not match [0-9], so a retract is needed to push back ;: emit NUMBER('007') with attribute lexeme = "007".
  6. Read ; => emit SEMICOLON. Final tokens (sequence): INT_KEYWORD, IDENTIFIER(count), ASSIGN, NUMBER(007), SEMICOLON.

Example 2 — two-buffer sentinel scheme with lexeme crossing buffer boundary Assume BUFSIZE = 8, input (no spaces) = identifier123+x (length 15). Buffers: Buffer A holds first 8 chars then sentinel; Buffer B holds next 7 chars then sentinel. Initial state: fill Buffer A (cells 0..7), sentinel at position 8; fill Buffer B only when needed. Trace with positions (index relative to each buffer):

  1. lexemeBegin at Buffer A index 0, forward moves reading i d e n t i f i (8 chars). Next getChar sees sentinel at end of A. Because sentinel is detected, the implementation refills the other buffer (Buffer B) with next chunk and sets forward to Buffer B index 0. The sentinel avoids an explicit per-character end-of-buffer test.
  2. Continue reading across boundary: read e, r, 1, 2, 3 in Buffer B. After 3 next char is +, which does not match identifier pattern, so stop. The lexeme from lexemeBegin to forward-1 spans Buffer A and Buffer B. Emit IDENTIFIER('identifier123') and set lexemeBegin to +.
  3. Read operator + and then x and finish. The two-buffer scheme made it unnecessary to copy lexeme or check buffer boundary per character; pointers and sentinel logic handle it.

Pseudocode (getChar, retract) — concise, exam-style:

`int getChar() { ch = character at forward; if (ch is sentinel) { fillBuffer(otherBuffer); move forward to start of otherBuffer; ch = character at forward; if (ch is sentinel) return EOF; // true end of file } forward++; return ch; }

void retract() { if (forward is at start of current buffer) { move forward to last non-sentinel character of otherBuffer; } else { forward--; } }

int getNextToken() { lexemeBegin = forward; state = START; while (true) { c = getChar(); state = DFA[state][c]; if (state is accepting and next input does not extend) { if (c is not part of token) retract(); return token for matched lexeme; } if (state is error) report lexical error; } } `

Common mistakes

  • Forgetting to retract after reading one char lookahead (drops a character or mis-reads the next token).
  • Implementing buffering but copying lexemes across buffer boundary instead of using pointers — slow and unnecessary.
  • Confusing EOF of file with buffer sentinel — sentinel is artificial and should not be emitted as token.
  • Using too small BUFSIZE in production code; using non-power-of-two sizes without reason (affects alignment/performance on some systems).

For your exam

Question types you will see:

  • Definitions: define token, lexeme, pattern, maximal-munch, scanner.
  • Short notes: describe input-buffering techniques, two-buffer scheme, sentinel method.
  • Derivations/algorithms: write pseudocode for getChar/retract and explain pointers and sentinel handling; draw buffer diagram.
  • Programs: a small scanner fragment in C showing buffers and getChar.
  • Diagrams: two-buffer layout and pointer movement — show lexemeBegin and forward crossing boundary.

What a full-marks answer includes:

  • Precise definitions with bold names (token, lexeme, pattern).
  • Statement of maximal-munch rule and its assumptions.
  • Correct diagram of two buffers with sentinels and labelled pointers.
  • Correct pseudocode for getChar, retract and getNextToken (show where refill happens).
  • Example trace or short test input showing crossing of buffer boundary and correct tokenization.

Quick check

  1. What is the difference between a lexeme and a token-name?
  2. State the maximal-munch rule in one sentence.
  3. Why use a sentinel at end of buffer in the two-buffer scheme?

Answers: 1) A lexeme is the actual sequence of characters from the source; a token-name is the symbolic category (e.g. IDENTIFIER) assigned to that lexeme. 2) The scanner selects the longest prefix of the unread input that matches any token pattern (ties broken by precedence). 3) A sentinel lets getChar detect end-of-buffer without testing bounds on every character-read; it triggers buffer refill efficiently and avoids per-character boundary checks.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?