This project is read-only.

Sript access to variables set by host using SetVariable

Jun 3, 2010 at 4:54 PM

I'm new to language implementation and am playing around with a sample created by lionel Laske.  My host code looks like this....


        static void Main(string[] args)
            // Create runtime
            ScriptRuntime runtime = ScriptRuntime.Create();

            // Load Engine
            ScriptEngine engine = runtime.GetEngine(typeof(ADT.DLR.ADTLanguageContext));

            ScriptScope scope = engine.CreateScope();

scope.SetVariable("testvar", 42); // Execute command ScriptSource src = engine.CreateScriptSourceFromString(""); src.Execute(scope); // Shutdown engine engine.Shutdown(); }


How do I access 'testvar' when putting together the AST (ADT.DLR.ADTLanguageContext.ParseSourceCode)?  I figured it would look something like:-


Expression testParam = program.CreateLocalVariable("testvar", typeof(Int32));


But it doesn't seem to pick up the value I set in the Host code.  Any Ideas?

BTW, I did see this post...  but I wasn't sure if it was relevant.

Jun 3, 2010 at 5:10 PM
First, you need to override CompileSourceCode on your LanguageContext:

public override ScriptCode CompileSourceCode(SourceUnit sourceUnit, CompilerOptions options, ErrorSink errorSink) This method produces an instance of a subclass of ScriptCode class. The class is abstract so you need to subclass it.
The only method you need to override in the subclass is
public override object Run(Scope scope)
This is called by the Hosting API when executing code against a scope. It's up to you how you pass the scope into the top-level code of your language. You might create a LambdaExpression that takes a Scope as a parameter. Scope is IDynamicMetaObjectProvider, so you can use Dynamic expressions with GetMember and SetMember binders to access the variables stored in it.
Check out and to see how we do this in Ruby.
Jun 5, 2010 at 5:16 AM

Oh, when I do a 'Go To Definition' on LanguageContext, i get...

namespace Microsoft.Scripting.Runtime
    public abstract class LanguageContext : ICloneable


    public abstract LambdaExpression ParseSourceCode(CompilerContext context);

no sign of a CompileSourceCode method.  Am I using an old version???

Name: Microsoft.Scripting

Path: ...\Microsoft.Scripting.dll


Jun 6, 2010 at 3:30 PM

Yes, that's an extremely old version of the DLR. I can't access the source history right now, but IronPython 2.0 shipped about 18 months ago and it's got the abstract CompileSourceCode member that Tomáš mentions.