Name shadowing in VHDL

Posted on 2015‑01‑26
by Philippe Faes

Like many other languages, it is possible in VHDL to perform name scoping. This happens if you declare a new object in a nested scope that reuses the name of an object that was already declared. This is not an error in VHDL, but it can be confusing and it can cause errors. In general, I would advice against name scoping unless you have a very good reason. Even then, it would be best if you document (comment) your code so that everybody understands what is going on.

This is a straightforward example of name shadowing:

entitye0isendentitye0;architecturedemoofe0isconstantc:integer:=1;beginassertc=1;myblock:blockconstantc:integer:=2;beginassertc=2report"the second declaration of constant c shadows the first";endblockmyblock;assertc=1report"this is the scope of the first declaration again";endarchitecturedemo;

It gets more confusing if you shadow names from the a standardized package:

A common misconception is that loop iterators need to be declared beforehand. They don't, because they are declared implicitly in the loop statement.

architecturedemo4ofe0isbeginprocessisvariablei:integer:=1;beginasserti=1;i:=5;asserti=5;foriin0to10loop-- this is a different object, shadowing the variable ireportinteger'image(i);-- i behaves like a constant herei:=i+1;-- error! cannot assign to constants!endloop;asserti=5;-- this is still the variable, declared in the processi:=i+1;asserti=6;wait;endprocess;endarchitecture;

Note: you can reach these shadowed names by using their expanded names:

entityfunisendentity;architecturehideoffunisbeginexample:processisvariablex:integer:=0;procedurechangevar(x:integer)isbeginhide.example.x:=x;-- or example.xendprocedure;beginchangevar(5);report"x="&integer'image(x);wait;endprocess;endarchitecture;