Are Camlp4 extensions lexical? Can you load some syntactic extension within a single function and have it apply within only that function's lexical scope?
If I understand Camlp4 correctly, it's essentially a pre-processor. It's a very powerful pre-processor, perhaps, but you'd probably have to work very deep magic to be able to replace the Ocaml parser for a lexical scope. This is not yet implemented, but eventually you'll be able to do 'supersede slang MAIN { ... }' and rewrite the grammar the current lexical scope.
How easy is it to use Camlp4 extensions from OCaml programs? In Perl 6, it's a simple matter of "use SomeModule;".
Here's the code of a module to provide a factorial operator.
module Factorial;
multi sub postfix:<!>(Mu $n) is export {
[*] 1..$n;
}
And an example of using it: use Factorial;
say 5!; # outputs 120
This is actually essentially how many of the built-in operators are provided in Rakudo. The ones that aren't provided in this way are the ones like || and && with short-circuiting semantics which need to be evaluated specially and the ones that are better implemented in PIR.I'm afraid I don't have any examples of more extensive grammar modifications, as Rakudo doesn't have much support for them yet. More accurately, it doesn't have support for adding them in mid-parse yet; it's fairly simple to create a new grammar class deriving from Rakudo's Perl6::Grammar with a few modifications and parse files with it.