ArticleslgStudy

science

Lexer hack

Lexer hack is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Lexer hack rather than just read about it. In short: In computer programming, the lexer hack is a solution to parsing a context-sensitive grammar such as C, where classifying a sequence of characters as a variable name or a type name requires contextual information, by feeding contextual information backwards from the parser to the lexer. The lexer hack is frowned upon in modern compilers as it creates tight coupling between otherwise largely independent steps in the…

Key takeaways

  • Lexer hack belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Lexer hack to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Lexer hack from memory before moving on to harder problems.

Reference excerpt

In computer programming, the lexer hack is a solution to parsing a context-sensitive grammar such as C, where classifying a sequence of characters as a variable name or a type name requires contextual information, by feeding contextual information backwards from the parser to the lexer. The lexer hack is frowned upon in modern compilers as it creates tight coupling between otherwise largely independent steps in the compilation process. Instead, identifier-like tokens are tokenized as identifiers and later disambiguated by the parser, allowing cleaner separation of concerns.

Problem The fundamental problem is differentiating types from other identifiers. In the following example, the lexical class of A cannot be determined without further contextual information:

This code could either be multiplication or a declaration, depending on context. In more detail, in a compiler, the lexer performs one of the earliest stages of converting the source code to a program. It scans the text to extract meaningful tokens, such as words, numbers, and strings. The parser analyzes sequences of tokens attempting to match them to syntax rules representing language structures, such as loops and variable declarations. A problem occurs here if a single sequence of tokens can ambiguously match more than one syntax rule. This ambiguity can happen in C if the lexer does not distinguish between variable and typedef identifiers. For example, in the C expression:

the lexer may find these tokens:

?? 'A' operator '*' identifier 'B' punctuation ';' Depending on whether A is a typedef name or not it may be desirable to tokenize A as either an identifier or a type so the parser does not have to handle an ambiguous parse. This grammatical ambiguity is known as the "typedef-name: identifier" problem, due to the name of the problematic production rule.

The hack solution The solution generally consists of feeding information from the semantic symbol table back into the lexer. That is, rather than functioning as a pure one-way pipeline from the lexer to the parser, there is a backchannel from semantic analysis back to the lexer. This mixing of parsing and semantic analysis is generally regarded as inelegant, which is why it is called a "hack". Without added context, the lexer cannot distinguish type identifiers from other identifiers because all identifiers have the same format. With the hack in the above example, when the lexer finds the identifier A it should be able to classify the token as a type identifier. The rules of the language would be clarified by specifying that typecasts require a type identifier and the ambiguity disappears. The problem also exists in C++ and parsers can use the same hack.

Alternative solutions This problem does not arise (and hence needs no "hack" in order to solve) when using lexerless parsing techniques, as these are intrinsically contextual. These are generally seen as less elegant designs, however, because they lack the modularity of having a concurrent lexer and parser in a pipeline. Some parser generators, such as the byacc-derived BtYacc ("Backtracking Yacc"), give the generated parser the ability to try multiple attempts to parse the tokens. In the problem described here, if an attempt fails because of semantic information about the identifier, it can backtrack and attempt other rules. The Clang parser handles the situation in a completely different way, namely by using a non-reference lexical grammar. Clang's lexer does not attempt to differentiate between type names and variable names: it simply reports the current token as an identifier. The parser then uses Clang's semantic analysis library to determine the nature of the identifier. This allows a simpler and more maintainable architecture than The Lexer Hack. This is also the approach used in most other modern languages, which do not distinguish different classes of identifiers in the lexical grammar, but instead defer them to the parsing or semantic analysis phase, when sufficient information is available.

See also Dangling else Most vexing parse

References

Citations http://www.cs.berkeley.edu/~smcpeak/elkhound/sources/elkhound/index.html http://cs.nyu.edu/rgrimm/papers/pldi06.pdf http://cens.ioc.ee/local/man/CompaqCompilers/ladebug/ladebug-manual-details.html Archived 2005-01-06 at the Wayback Machine DOI.org [link removed] http://groups.google.com/group/comp.compilers/browse_frm/thread/db7f68e9d8b49002/fa20bf5de9c73472?lnk=st&q=%2B%22the+lexer+hack%22&rnum=1&hl=en#fa20bf5de9c73472

Worked examples

Example 1 — a first encounter with Lexer hack

Start with the simplest possible case. Write down what Lexer hack claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Lexer hack before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Lexer hack ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Lexer hack

In research
Lexer hack appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Lexer hack in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Lexer hack is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, C (programming language), Parsing, so understanding it makes those chapters shorter.
In everyday life
Look for Lexer hack outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Lexer hack in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Lexer hack means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Lexer hack out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Lexer hack in simple terms?

In computer programming, the lexer hack is a solution to parsing a context-sensitive grammar such as C, where classifying a sequence of characters as a variable name or a type name requires contextual information, by feeding contextual information backwards from the parser to the lexer. The lexer h…

Why does Lexer hack matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Lexer hack?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Lexer hack.

Tags

  • C++
  • C (programming language)
  • Parsing

Keep exploring