Assume I'm reading a package file and want to know the current $Context while going serially through the file. I want to do this by inspecting the arguments of each Begin and BeginPackage, and by collecting all End and EndPackage to maintain a stack or list of contexts. This stack is then used to build the $Context.
I'm mainly interested in whether my understanding of the situation is correct, how to build the current context and in the stability of the approach. Here are some examples, starting with the most trivial one
p[] := Print[$Context]
BeginPackage["P`"];
Global`p[];
Begin["`Private`"];
Global`p[];
End[];
Global`p[];
EndPackage[];
Here Begin is used to replace the context rather than appending a sub-context
BeginPackage["P`"];
Global`p[];
Begin["New`"];
Global`p[];
End[];
Global`p[];
EndPackage[];
See, that Begin and BeginPackage can be mixed up. That does influence $ContextPath but not how $Context is build up:
BeginPackage["P`"];
Global`p[];
Begin["`New`"];
Global`p[];
EndPackage[];
Global`p[];
End[];
In the first example, in the most inner call to p[], I would have collected {"P`","`Private`"}, in the second example {"P`","New`"}. Am I correct in the following assumptions
- A (sub-)context always needs to end in
` - Every element in my context list that does not start with a
`, like e.g.P`starts a new context. Relative contexts like`Rel`are always appended - every
EndorEndPackagedrops the last element of my context-list
Finally, beside the ugly \[Alpha] are there any special characters allowed in a context? Would it be OK to assume the following regex for a relative context?
`(([a-zA-Z$]+[0-9]*)+`)+



Begin["123`"]gives a tip:A context must consist of valid symbol names separated by and ending with `and valid symbol names are in documentation somewhere. – Kuba Dec 18 '16 at 12:35$is also allowed in context names. – Szabolcs Dec 18 '16 at 12:50$as Szabolcs pointed out but nothing else. – halirutan Dec 18 '16 at 12:52"`foo`"is immediately expanded to$Context`foo`. It would be better to collectP`Private`instead of"`Private`"because"`Private`"can't even be interpreted without a current value of$Context. (I had to use some"in this comment to make the markdown converter do what I wanted.) – Szabolcs Dec 18 '16 at 12:55[a-zA-Z$]+[a-zA-Z$0-9]*I think – Szabolcs Dec 18 '16 at 12:59