-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scripts.cs
209 lines (182 loc) · 8.71 KB
/
Scripts.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using TaleWorlds.CampaignSystem;
using TaleWorlds.Library;
using StringWriter = System.IO.StringWriter;
namespace Int19h.Bannerlord.CSharp.Scripting {
public class Scripts : DynamicObject {
internal static readonly string SharedLocation = Path.Combine(
Path.GetDirectoryName(typeof(Scripts).Assembly.Location),
"Scripts"
);
internal static readonly string UserLocation = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Mount and Blade II Bannerlord",
"Scripts"
);
internal static readonly string RspFilePath = Path.Combine(
Path.GetTempPath(),
"Int19h.Bannerlord.CSharp.Scripting.rsp"
);
static Scripts() {
using (var writer = File.CreateText(RspFilePath)) {
writer.WriteLine("# DO NOT EDIT THIS FILE!");
writer.WriteLine("# It is automatically generated by the C# Scripting mod, and will be overwritten.");
writer.WriteLine();
writer.WriteLine($"/r:\"{typeof(ScriptGlobals).Assembly.Location}\"");
writer.WriteLine($"/r:\"{typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location}\"");
var nss = new HashSet<string>();
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
if (asm.IsDynamic || string.IsNullOrEmpty(asm.Location)) {
continue;
}
writer.WriteLine($"/r:\"{asm.Location}\"");
foreach (var type in asm.GetExportedTypes()) {
var ns = type.Namespace;
if (ns != null && (ns.StartsWith("TaleWorlds") || ns.StartsWith("SandBox"))) {
nss.Add(ns);
}
}
}
writer.WriteLine();
writer.WriteLine("/u:System");
writer.WriteLine("/u:System.Collections.Generic");
writer.WriteLine("/u:System.Linq");
writer.WriteLine("/u:System.Reflection");
writer.WriteLine("/u:System.Text");
foreach (var ns in nss) {
writer.WriteLine($"/u:{ns}");
}
writer.WriteLine($"/u:{typeof(ScriptGlobals).FullName}");
writer.WriteLine();
foreach (var loadPath in GetSearchPaths()) {
writer.WriteLine($"/loadpath:\"{loadPath}\"");
}
writer.WriteLine();
var gameAppVer = ApplicationVersion.FromParametersFile();
var gameVer = new Version(gameAppVer.Major, gameAppVer.Minor, gameAppVer.Revision);
for (var major = 1; major < 10; ++major) {
for (var minor = 6; minor < 10; ++minor) {
for (var release = 0; release < 20; ++release) {
var ver = new Version(major, minor, release);
if (ver <= gameVer) {
writer.WriteLine($"/d:BANNERLORD_{major}_{minor}_{release}");
}
}
}
}
}
}
internal static IEnumerable<string> GetSearchPaths() {
if (Campaign.Current?.UniqueGameId is string gameId) {
yield return Path.Combine(UserLocation, "Campaigns", gameId);
}
yield return UserLocation;
yield return SharedLocation;
}
internal static ScriptOptions GetScriptOptions() {
var baseDir = Path.GetDirectoryName(RspFilePath);
var sdkDir = Path.GetDirectoryName(typeof(object).GetType().Assembly.ManifestModule.FullyQualifiedName);
var rsp = CSharpCommandLineParser.Script.Parse(new[] { $"@{RspFilePath}" }, baseDir, sdkDir);
var refs = rsp.ResolveMetadataReferences(ScriptMetadataResolver.Default);
var sourceResolver = ScriptSourceResolver.Default.WithSearchPaths(GetSearchPaths());
return ScriptOptions.Default
.WithEmitDebugInformation(true)
.WithSourceResolver(sourceResolver)
.AddReferences(refs)
.AddImports(rsp.CompilationOptions.Usings);
}
internal static void IgnoreVisibility(Microsoft.CodeAnalysis.Scripting.Script script) {
var options = (CSharpCompilationOptions)script.GetCompilation().Options;
var metadataImportOptionsProperty = typeof(CompilationOptions).GetProperty("MetadataImportOptions", BindingFlags.Instance | BindingFlags.Public);
metadataImportOptionsProperty.SetValue(options, MetadataImportOptions.All);
var topLevelBinderFlagsProperty = typeof(CSharpCompilationOptions).GetProperty("TopLevelBinderFlags", BindingFlags.Instance | BindingFlags.NonPublic);
var flags = (uint)topLevelBinderFlagsProperty.GetValue(options);
const uint IgnoreAccessibility = 1u << 22;
flags |= IgnoreAccessibility;
topLevelBinderFlagsProperty.SetValue(options, flags);
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
result = new Script(binder.Name);
return true;
}
}
public class Script : DynamicObject {
public delegate void Invoker(dynamic?[] args);
private string Name { get; }
private string FileName => Name + ".csx";
private ScriptState State { get; set; }
public Script(string name) {
Name = name;
var script = CSharpScript.Create<Action<object?[]>>($"#load \"{FileName}\"", Scripts.GetScriptOptions());
Scripts.IgnoreVisibility(script);
State = script.RunAsync().GetAwaiter().GetResult();
}
public override bool TryInvoke(InvokeBinder binder, object?[] args, out object? result) {
result = Invoke(Name, binder.CallInfo, args);
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object?[] args, out object? result) {
result = Invoke(binder.Name, binder.CallInfo, args);
return true;
}
private object? Invoke(string funcName, CallInfo callInfo, object?[] args) {
int posCount = callInfo.ArgumentCount - callInfo.ArgumentNames.Count;
var argNames = Enumerable.Repeat((string?)null, posCount).Concat(callInfo.ArgumentNames).ToArray();
Invoker GetInvoker(bool construct) {
var code = new StringWriter();
code.WriteLine($"#line 1 \"{FileName}\"");
code.Write("return (global::Int19h.Bannerlord.CSharp.Scripting.Script.Invoker)(args => ");
if (construct) {
code.Write("new ");
}
code.Write($"{funcName}(");
for (int i = 0; i < args.Length; ++i) {
if (i != 0) {
code.Write(", ");
}
var argName = argNames[i];
if (argName != null) {
code.Write($"{argName}: ");
}
code.Write($"args[{i}]");
}
code.WriteLine("));");
var script = State.Script.ContinueWith<Invoker>(code.ToString());
Scripts.IgnoreVisibility(script);
try {
return script.RunAsync().GetAwaiter().GetResult().ReturnValue;
} catch (CompilationErrorException) {
if (construct) {
return GetInvoker(false);
} else {
throw;
}
}
}
var invoker = GetInvoker(false);
var oldScriptPath = ScriptGlobals.ScriptPath;
ScriptGlobals.ScriptPath = FileName;
args = args.Select(arg => ScriptArgument.Wrap(arg)).ToArray();
try {
invoker(args);
return null;
} catch (TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
} finally {
ScriptGlobals.ScriptPath = oldScriptPath;
}
}
}
}