Unexpected scoping issue using \XeTeXinterchartoks

Minimal example (compile with xetex):

\XeTeXinterchartokenstate = 1
\newXeTeXintercharclass \classa
\XeTeXcharclass \a \classa
\XeTeXinterchartoks 255 \classa = {\begingroup}
\XeTeXinterchartoks \classa 255 = {\endgroup}

\def\foo{\csname MaybeUndefined\endcsname}

\tracingall

a\foo

\bye


What I get:

{the letter a}
{horizontal mode: the letter a}
\XeTeXinterchartoks->\begingroup
{\begingroup}
{entering semi simple group (level 1) at line 11}
{the letter a}

\foo ->\csname MaybeUndefined\endcsname
{\csname}
{changing \MaybeUndefined=undefined}
{into \MaybeUndefined=\relax}
{\relax}
\XeTeXinterchartoks->\endgroup
{\endgroup}
{restoring \MaybeUndefined=undefined}
{leaving semi simple group (level 1) entered at line 11}
{undefined}
! Undefined control sequence.

l.11 a\foo


Here, \csname MaybeUndefined\endcsname should expand to \MaybeUndefined and then \relax. However, after inserting an \endgroup by \XeTeXinterchartoks, \MaybeUndefined is undefined again after the group. Then the unexpected error occurs.

What can I do?

-
I would say it depends which part of the code is under your control. You can add a \relax at the start of \foo. But if \foo represents an arbitrary command then imho you are out of luck: xetex has to go forth to check if the next input is a word boundary and then must go "back" to insert your \endgroup. –  Ulrike Fischer May 1 '12 at 17:19
@UlrikeFischer: Well, we are developing packages rely on \XeTeXinterchartoks, but we cannot determine how users use it. So it is not possible to add \relax before \foo. For some cases, I can reimplement \@namedef to avoid the problem, but that's not enough. –  Leo Liu May 2 '12 at 5:54
@UlrikeFischer Can you convert your comment to an answer? I believe that this cannot be solved in full generality. –  egreg Oct 6 '12 at 22:22

I would say it depends which part of the code is under your control. You can add a \relax at the start of \foo. But if \foo represents an arbitrary command then imho you are out of luck: xetex has to go forth to check if the next input is a word boundary and then must go "back" to insert your \endgroup`.