Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load referenced script libraries from a Roslyn script file?

Tags:

c#

roslyn

I figured out I cannot load one script library from another easily:

module.csx

string SomeFunction() {
   return "something";
}

script.csx

ExecuteFile("module.csx");
SomeFunction() <-- causes compile error "SomeFunction" does not exist

This is because the compiler does not know of module.csx at the time it compiles script.csx afaiu. I can add another script to load the two files from that one, and that will work. However thats not that pretty.

Instead I like to make my scripthost check for a special syntax "load module" within my scripts, and execute those modules before actual script execution.

script.csx

// load "module.csx"
SomeFunction()

Now, with some basic string handling, I can figure out which modules to load (lines that contains // load ...) and load that files (gist here https://gist.github.com/4147064):

foreach(var module in scriptModules) {
   session.ExecuteFile(module);
}
return session.Execute(script)

But - since we're talking Roslyn, there should be some nice way to parse the script for the syntax I'm looking for, right?

And it might even exist a way to handle module libraries of code?

like image 916
joeriks Avatar asked Nov 25 '12 23:11

joeriks


3 Answers

Currently in Roslyn there is no way to reference another script file. We are considering moving #load from being a host command of the Interactive Window to being a part of the language (like #r), but it isn't currently implemented.

As to how to deal with the strings, you could parse it normally, and then look for pre-processor directives that are of an unknown type and delve into the structure that way.

like image 176
Kevin Pilch Avatar answered Nov 16 '22 02:11

Kevin Pilch


Support for #load in script files has been added as of https://github.com/dotnet/roslyn/commit/f1702c.

This functionality will be available in Visual Studio 2015 Update 1.

like image 44
Kevin Halverson Avatar answered Nov 16 '22 00:11

Kevin Halverson


Include the script:

#load "common.csx"
...

And configure the source resolver when you run the scripts:

Script<object> script = CSharpScript.Create(code, ...);
var options = ScriptOptions.Default.WithSourceResolver(new SourceFileResolver(new string[] { }, baseDirectory));
var func = script.WithOptions(options).CreateDelegate()
...
like image 36
turdus-merula Avatar answered Nov 16 '22 00:11

turdus-merula