I will explain what I mean by restricted scope first:
restrictedScope (allowedNamespace) {
/* THE CLIENT CODE GOES HERE */
/* the namespace in this closure is limited only to the idioms
I allow, both in terms of reserved words and standard functions */
val result = allowedNamespace.run(); // works, since run() ...
// ... is a function of allowedNamespace
val list = new List(); // does not work, since List is not in scope
/* CLIENT CODE SAMPLE (prepare, release and wait are defined in allowedNamespace) */
prepare( "service 1" )
wait( 1000 )
release( "service 1" )
...
}
While executing a strictly imperative DSL based on regular scala code, I would like to run the client code safely. And to do this safely, I might want to restrict the usage of constructions like for and if (only if possible), remove the creation of lists and allow only the idioms I define in allowed namespace to be executed/referred to.
Are there facilities to do this, without overriding all standard idioms?
If not, is there an automatic way (probably via reflection) to override all standard idioms imported to the namespace?
This might be possible to do with experimental macros in Scala 2.10 which would allow you to inspect the code inside
restrictedScopebefore compiling.However, I think you’ll have a hard time filtering the tree for allowed and forbidden methods. So I am not sure this is feasible.
Alternatively, you could make use of the experimental scala-virtualized branch which at least would allow you to simply overload
forandifstatements to your own liking. (Reference)Yet, this also requires shipping your own compiler so it really depends on the scope of your problem and the target user base. (Some more info on Scala DSLs.)