forked from SergiyStoyan/PdfDocumentParser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompiler.cs
185 lines (174 loc) · 8.47 KB
/
Compiler.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
//********************************************************************************************
//Author: Sergiy Stoyan
// s.y.stoyan@gmail.com, sergiy.stoyan@outlook.com, stoyan@cliversoft.com
// http://www.cliversoft.com
//********************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Cliver.PdfDocumentParser
{
/// <summary>
/// Tool for hot-compiling assembly from C# code string
/// </summary>
public class Compiler
{
[Serializable]
public class Error
{
public int P1;
public int P2;
public string Message;
}
public class Exception : System.Exception
{
public Exception(List<Error> compilationErrors) : base(string.Join("\r\n", compilationErrors.Select(a => a.Message)))
{
for (int i = 0; i < compilationErrors.Count; i++)
Data[i] = compilationErrors[i];
}
}
//static HashSet<string> assemblyPaths = new HashSet<string>
//{
// typeof(object).Assembly.Location, //mscorlib
// //MetadataReference.CreateFromFile(typeof(DynamicObject).Assembly.Location), //System.Core
// //MetadataReference.CreateFromFile(typeof(RuntimeBinderException).Assembly.Location),//Microsoft.CSharp
// //MetadataReference.CreateFromFile(typeof(Action).Assembly.Location), //System.Runtime
// //MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location),
// //MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location),
// //MetadataReference.CreateFromFile(typeof(System.Text.RegularExpressions.Regex).Assembly.Location),
// typeof(System.Drawing.Size).Assembly.Location,
// typeof(System.Drawing.Point).Assembly.Location,
// typeof(System.Drawing.Bitmap).Assembly.Location,
// //MetadataReference.CreateFromFile(typeof(Cliver.DateTimeRoutines).Assembly.Location),
// typeof(Emgu.CV.Structure.Gray).Assembly.Location,
// typeof(Emgu.CV.IColor).Assembly.Location,
// typeof(Emgu.CV.CvInvoke).Assembly.Location,
// typeof(Emgu.CV.CvEnum.AdaptiveThresholdType).Assembly.Location,
// Assembly.GetExecutingAssembly().Location,
//};
//static List<MetadataReference> _references = new List<MetadataReference>();
//static Compiler()
//{
// // foreach (string ap in assemblyPaths)
// // references.Add(MetadataReference.CreateFromFile(ap));
// //foreach (AssemblyName an in typeof(Emgu.CV.Structure.Gray).Assembly.GetReferencedAssemblies())
// // assemblyPaths.Add(Assembly.Load(an.FullName).Location);
// //references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location)); //netstandard
// //references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location)); //netstandard
//}
//public static void Test()
//{
// Stopwatch sw0 = new Stopwatch();
// sw0.Start();
// var f = references;
// sw0.Stop();
// Stopwatch sw1 = new Stopwatch();
// sw1.Start();
// var r = references;
// sw1.Stop();
// Stopwatch sw3 = new Stopwatch();
// sw3.Start();
// var y = references;
// sw3.Stop();
//}
static public List<MetadataReference> GetAllReferences(Assembly rootAssembly)
{
List<MetadataReference> references = new List<MetadataReference>();
Dictionary<string, Assembly> assemblNames2assemby = new Dictionary<string, Assembly>();
getAllAssemblies(assemblNames2assemby, rootAssembly);
foreach (Assembly a in assemblNames2assemby.Values)
references.Add(MetadataReference.CreateFromFile(a.Location));
return references;
}
static void getAllAssemblies(Dictionary<string, Assembly> assemblNames2assemby, Assembly assembly)
{
assemblNames2assemby[assembly.FullName] = assembly;
foreach (AssemblyName an in assembly.GetReferencedAssemblies())
if (!assemblNames2assemby.ContainsKey(an.FullName))
{
try
{
Assembly a = Assembly.Load(an);
getAllAssemblies(assemblNames2assemby, a);
}
catch (System.IO.FileNotFoundException)//some assemblies could not be loaded but they seem to be non needed
{
}
}
}
/// <summary>
/// Compile
/// </summary>
/// <param name="typeDefinition"></param>
/// <param name="references"></param>
/// <param name="dllFile"></param>
/// <returns></returns>
public static Type[] Compile(string typesDefinition, Assembly rootAssembly, string dllFile = null)
{
return compile(typesDefinition, null, rootAssembly, dllFile);
}
public static Type[] Compile(string typesDefinition, IEnumerable<MetadataReference> references, string dllFile = null)
{
return compile(typesDefinition, references, null, dllFile);
}
static Type[] compile(string typesDefinition, IEnumerable<MetadataReference> references = null, Assembly rootAssembly = null, string dllFile = null)
{
SyntaxTree st = SyntaxFactory.ParseSyntaxTree(typesDefinition);
CSharpCompilation compilation = CSharpCompilation.Create("emitted.dll",//no file seems to be really created
syntaxTrees: new SyntaxTree[] { st },
references: references != null ? references : GetAllReferences(rootAssembly),
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
Assembly assembly;
void checkEmitResult(Microsoft.CodeAnalysis.Emit.EmitResult result)
{
if (!result.Success)
{
List<Error> compilationErrors = new List<Error>();
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
compilationErrors.Add(new Error { Message = diagnostic.GetMessage(), P1 = diagnostic.Location.SourceSpan.Start, P2 = diagnostic.Location.SourceSpan.End });
throw new Exception(compilationErrors);
}
}
if (dllFile == null)
using (var ms = new MemoryStream())
{
Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms);
checkEmitResult(result);
ms.Seek(0, SeekOrigin.Begin);
assembly = Assembly.Load(ms.ToArray());
}
else
{
Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(dllFile);
checkEmitResult(result);
assembly = Assembly.Load(dllFile);
}
return assembly.GetTypes();
}
public static IEnumerable<Type> FindSubTypes(string baseTypeName, Type[] types)
{
return types.Where(t => !t.IsAbstract && t.BaseType.FullName.Contains(baseTypeName));
}
public static IEnumerable<Type> FindSubTypes(Type baseType, Type[] types)
{
return types.Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t));
}
public static string RemoveComments(string typesDefinition)
{
if (typesDefinition == null)
return null;
typesDefinition = Regex.Replace(typesDefinition, @"^\s*//.*", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
return Regex.Replace(typesDefinition, @"/\*.*?\*/", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
//return Regex.Replace(typesDefinition, @"\s+", "", RegexOptions.Singleline);
}
}
}