Have read in Compiler textbook that type inference is context sensitive. Can anyone explain why is it so? This means that we need context sensitive grammar in semantic analysis phase of a compiler with this feature? How is it done in popular programming languages like C?


The context that is needed tells us the types of known variables. Suppose We want to infer the type of

if b or 2 = x then a else b

To make sense of this we need to

  1. Check that the type of b is bool
  2. That the type of x is numeric
  3. That a and b have the same type.

To answer these three questions, we look up information about variables in a typing context, which is a mapping from variables to their types. Furthermore, the result is context-sensitive, as the type of the whole expression is the type of a (and b), which is given by the information in the context.

Now you are also mentioning grammars. These are not really relevant here, because we are talking about a stage of compilation which comes after parsing. I think you just got confused by the word "context" being used outside of the subject of grammars. Or you are reading a very strange book. By the way, there is a reason scientists want other scientists to give precise references to their sources. So instead of saying "I read a compiler book", you should have given the author and the title. Now I am just guessing.

| cite | improve this answer | |
  • $\begingroup$ I was referring Engineering a Compiler by Keith D Cooper $\endgroup$ – user5507 Jan 7 '13 at 1:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.