-
Notifications
You must be signed in to change notification settings - Fork 64
/
Compiler.cs
527 lines (454 loc) · 23.1 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Name: Compiler.cs
// Description: .NET Assembly Generator
// Author: Tim Chipman
// Origination: Work performed for BuildingSmart International Ltd. and Georgia Tech by Constructivity.com LLC.
// Copyright: (c) 2012-2014 BuildingSmart International Ltd., (c) 2014 Georgia Tech
// License: http://www.buildingsmart-tech.org/legal
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using IfcDoc.Schema;
using IfcDoc.Schema.DOC;
namespace IfcDoc
{
public class Compiler
{
private DocProject m_project;
private DocModelView[] m_views;
private AssemblyBuilder m_assembly;
private ModuleBuilder m_module;
private Dictionary<string, DocDefinition> m_definitions;
private Dictionary<string, Type> m_types;
private Dictionary<Type, Dictionary<string, FieldInfo>> m_fields;
private Dictionary<DocTemplateDefinition, MethodInfo> m_templates;
public Compiler(DocProject project, DocModelView[] views)
{
this.m_project = project;
this.m_views = views;
this.m_assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("IFC4"), AssemblyBuilderAccess.RunAndSave);
this.m_module = this.m_assembly.DefineDynamicModule("IFC4.dll", "IFC4.dll");
this.m_definitions = new Dictionary<string, DocDefinition>();
this.m_types = new Dictionary<string, Type>();
this.m_fields = new Dictionary<Type, Dictionary<string, FieldInfo>>();
this.m_templates = new Dictionary<DocTemplateDefinition, MethodInfo>();
Dictionary<DocObject, bool> included = null;
if (this.m_views != null)
{
included = new Dictionary<DocObject, bool>();
foreach (DocModelView docView in this.m_views)
{
this.m_project.RegisterObjectsInScope(docView, included);
}
}
foreach (DocSection docSection in project.Sections)
{
foreach (DocSchema docSchema in docSection.Schemas)
{
foreach (DocEntity docEntity in docSchema.Entities)
{
//if (included == null || included.ContainsKey(docEntity))
{
this.m_definitions.Add(docEntity.Name, docEntity);
}
}
foreach (DocType docType in docSchema.Types)
{
//if (included == null || included.ContainsKey(docType))
{
this.m_definitions.Add(docType.Name, docType);
}
}
}
}
foreach (string key in this.m_definitions.Keys)
{
RegisterType(key);
}
// seal types once all are built
List<TypeBuilder> listBase = new List<TypeBuilder>();
foreach (string key in this.m_definitions.Keys)
{
Type tOpen = this.m_types[key];
while (tOpen is TypeBuilder)
{
listBase.Add((TypeBuilder)tOpen);
tOpen = tOpen.BaseType;
}
// seal in base class order
for (int i = listBase.Count - 1; i >= 0; i--)
{
Type tClosed = listBase[i].CreateType();
this.m_types[tClosed.Name] = tClosed;
}
listBase.Clear();
}
}
public AssemblyBuilder Assembly
{
get
{
return this.m_assembly;
}
}
public ModuleBuilder Module
{
get
{
return this.m_module;
}
}
public FieldInfo RegisterField(Type type, string field)
{
while (type != null)
{
Dictionary<string, FieldInfo> map = this.m_fields[type];
FieldInfo fieldinfo = null;
if (map.TryGetValue(field, out fieldinfo))
{
return fieldinfo;
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Creates or returns emitted type, or NULL if no such type.
/// </summary>
/// <param name="map"></param>
/// <param name="typename"></param>
/// <returns></returns>
public Type RegisterType(string strtype)
{
// this implementation maps direct and inverse attributes to fields for brevity; a production implementation would use properties as well
if (strtype == null)
return typeof(SEntity);
Type type = null;
// resolve standard types
switch (strtype)
{
case "INTEGER":
type = typeof(long);
break;
case "REAL":
case "NUMBER":
type = typeof(double);
break;
case "BOOLEAN":
case "LOGICAL":
type = typeof(bool);
break;
case "STRING":
type = typeof(string);
break;
case "BINARY":
case "BINARY (32)":
type = typeof(byte[]);
break;
}
if (type != null)
return type;
// check for existing mapped type
if (this.m_types.TryGetValue(strtype, out type))
{
return type;
}
// look up
DocDefinition docType = null;
if (!this.m_definitions.TryGetValue(strtype, out docType))
return null;
// not yet exist: create it
TypeAttributes attr = TypeAttributes.Public;
if (docType is DocEntity)
{
attr |= TypeAttributes.Class;
DocEntity docEntity = (DocEntity)docType;
if (docEntity.IsAbstract())
{
attr |= TypeAttributes.Abstract;
}
Type typebase = RegisterType(docEntity.BaseDefinition);
// calling base class may result in this class getting defined (IFC2x3 schema with IfcBuildingElement), so check again
if (this.m_types.TryGetValue(strtype, out type))
{
return type;
}
TypeBuilder tb = this.m_module.DefineType(docType.Name, attr, typebase);
// add typebuilder to map temporarily in case referenced by an attribute within same class or base class
this.m_types.Add(strtype, tb);
// interfaces implemented by type (SELECTS)
foreach (DocDefinition docdef in this.m_definitions.Values)
{
if (docdef is DocSelect)
{
DocSelect docsel = (DocSelect)docdef;
foreach (DocSelectItem dsi in docsel.Selects)
{
if (strtype.Equals(dsi.Name))
{
// register
Type typeinterface = this.RegisterType(docdef.Name);
tb.AddInterfaceImplementation(typeinterface);
}
}
}
}
Dictionary<string, FieldInfo> mapField = new Dictionary<string, FieldInfo>();
this.m_fields.Add(tb, mapField);
ConstructorInfo conMember = typeof(DataMemberAttribute).GetConstructor(new Type[] { typeof(int) });
ConstructorInfo conLookup = typeof(DataLookupAttribute).GetConstructor(new Type[] { typeof(string) });
int order = 0;
foreach (DocAttribute docAttribute in docEntity.Attributes)
{
// exclude derived attributes
if (String.IsNullOrEmpty(docAttribute.Derived))
{
Type typefield = RegisterType(docAttribute.DefinedType);
if (docAttribute.AggregationType != 0)
{
typefield = typeof(List<>).MakeGenericType(new Type[] { typefield });
}
//todo: optional field...
FieldBuilder fb = tb.DefineField(docAttribute.Name, typefield, FieldAttributes.Public); // public for now
mapField.Add(docAttribute.Name, fb);
if (String.IsNullOrEmpty(docAttribute.Inverse))
{
// direct attributes are fields marked for serialization
CustomAttributeBuilder cb = new CustomAttributeBuilder(conMember, new object[] { order });
fb.SetCustomAttribute(cb);
order++;
}
else
{
// inverse attributes are fields marked for lookup
CustomAttributeBuilder cb = new CustomAttributeBuilder(conLookup, new object[] { docAttribute.Inverse });
fb.SetCustomAttribute(cb);
}
}
}
// find associated ConceptRoot for model view, define validation function
if (this.m_views != null)
{
foreach (DocModelView view in this.m_views)
{
string viewname = view.Code;
foreach (DocConceptRoot root in view.ConceptRoots)
{
if (root.ApplicableEntity == docEntity)
{
foreach (DocTemplateUsage concept in root.Concepts)
{
// bool ConceptTemplateA([Parameter1, ...]);
// {
// // for loading reference value:
// .ldfld [AttributeRule]
// .ldelem [Index] // for collection, get element by index
// .castclass [EntityRule] for entity, cast to expected type;
// // for object graphs, repeat the above instructions to load value
//
// for loading constant:
// .ldstr 'value'
//
// for comparison functions:
// .cge
//
// for logical aggregations, repeat each item, pushing 2 elements on stack, then run comparison
// .or
//
// return the boolean value on the stack
// .ret;
// }
// bool[] ConceptA()
// {
// bool[] result = new bool[2];
//
// if parameters are specified, call for each template rule; otherwise call just once
// result[0] = ConceptTemplateA([Parameter1, ...]); // TemplateRule#1
// result[1] = ConceptTemplateA([Parameter1, ...]); // TemplateRule#2
//
// return result;
// }
// compile a method for the template definition, where parameters are passed to the template
if (concept.Definition != null)
{
MethodInfo methodTemplate = this.RegisterTemplate(concept.Definition);
string methodname = viewname + "_" + concept.Definition.Name.Replace(' ', '_').Replace(':', '_').Replace('-', '_');
MethodBuilder method = tb.DefineMethod(methodname, MethodAttributes.Public, CallingConventions.HasThis, typeof(bool[]), null);
ILGenerator generator = method.GetILGenerator();
if (concept.Items != null && concept.Items.Count > 0)
{
// allocate array of booleans, store as local variable
generator.DeclareLocal(typeof(bool[]));
generator.Emit(OpCodes.Ldc_I4, concept.Items.Count);
generator.Emit(OpCodes.Newarr, typeof(bool));
generator.Emit(OpCodes.Stloc_0);
DocModelRule[] parameters = concept.Definition.GetParameterRules();
// call for each item with specific parameters
for (int row = 0; row < concept.Items.Count; row++)
{
DocTemplateItem docItem = concept.Items[row];
generator.Emit(OpCodes.Ldloc_0); // push the array object onto the stack, for storage later
generator.Emit(OpCodes.Ldc_I4, row); // push the array index onto the stack for storage later
generator.Emit(OpCodes.Ldarg_0); // push the *this* pointer for the IFC object instance
// push parameters onto stack
for (int col = 0; col < parameters.Length; col++)
{
DocModelRule docParam = parameters[col];
string paramvalue = docItem.GetParameterValue(docParam.Identification);
if (paramvalue != null)
{
//TODO: support other types such as integer, real, enum
generator.Emit(OpCodes.Ldstr, paramvalue);
}
else
{
generator.Emit(OpCodes.Ldnull);
}
}
generator.Emit(OpCodes.Call, methodTemplate); // call the validation function for the concept template
generator.Emit(OpCodes.Stelem_I); // store the result (bool) into an array slot
// VERIFY: is bool size dependent on platform (32/64?)
}
// return the array of boolean results
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
}
else
{
// allocate array of booleans, store as local variable
generator.DeclareLocal(typeof(bool[]));
generator.Emit(OpCodes.Ldc_I4, 1);
generator.Emit(OpCodes.Newarr, typeof(bool));
generator.Emit(OpCodes.Stloc_0);
generator.Emit(OpCodes.Ldloc_0); // push the array object onto the stack, for storage later
generator.Emit(OpCodes.Ldc_I4, 0); // push the array index onto the stack for storage later
// call once
generator.Emit(OpCodes.Ldarg_0); // push the *this* pointer for the IFC object instance
generator.Emit(OpCodes.Call, methodTemplate); // call the validation function for the concept template
generator.Emit(OpCodes.Stelem_I4); // store the result (bool) into an array slot
// return the array of boolean results
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
}
}
}
}
}
}
}
// remove from typebuilder
this.m_types.Remove(strtype);
type = tb; // avoid circular conditions -- generate type afterwords
}
else if (docType is DocSelect)
{
attr |= TypeAttributes.Interface | TypeAttributes.Abstract;
TypeBuilder tb = this.m_module.DefineType(docType.Name, attr);
// interfaces implemented by type (SELECTS)
foreach (DocDefinition docdef in this.m_definitions.Values)
{
if (docdef is DocSelect)
{
DocSelect docsel = (DocSelect)docdef;
foreach (DocSelectItem dsi in docsel.Selects)
{
if (strtype.Equals(dsi.Name))
{
// register
Type typeinterface = this.RegisterType(docdef.Name);
tb.AddInterfaceImplementation(typeinterface);
}
}
}
}
type = tb.CreateType();
}
else if (docType is DocEnumeration)
{
DocEnumeration docEnum = (DocEnumeration)docType;
EnumBuilder eb = this.m_module.DefineEnum(docType.Name, TypeAttributes.Public, typeof(int));
for (int i = 0; i < docEnum.Constants.Count; i++)
{
DocConstant docConst = docEnum.Constants[i];
eb.DefineLiteral(docConst.Name, (int)i);
}
type = eb.CreateType();
}
else if (docType is DocDefined)
{
DocDefined docDef = (DocDefined)docType;
TypeBuilder tb = this.m_module.DefineType(docType.Name, attr, typeof(ValueType));
// interfaces implemented by type (SELECTS)
foreach (DocDefinition docdef in this.m_definitions.Values)
{
if (docdef is DocSelect)
{
DocSelect docsel = (DocSelect)docdef;
foreach (DocSelectItem dsi in docsel.Selects)
{
if (strtype.Equals(dsi.Name))
{
// register
Type typeinterface = RegisterType(docdef.Name);
tb.AddInterfaceImplementation(typeinterface);
}
}
}
}
Type typeliteral = RegisterType(docDef.DefinedType);
if (docDef.Aggregation != null && docDef.Aggregation.AggregationType != 0)
{
typeliteral = typeof(List<>).MakeGenericType(new Type[] { typeliteral });
}
else
{
FieldInfo fieldval = typeliteral.GetField("Value");
while (fieldval != null)
{
typeliteral = fieldval.FieldType;
fieldval = typeliteral.GetField("Value");
}
}
FieldBuilder fieldValue = tb.DefineField("Value", typeliteral, FieldAttributes.Public);
type = tb.CreateType();
Dictionary<string, FieldInfo> mapField = new Dictionary<string, FieldInfo>();
mapField.Add("Value", fieldValue);
this.m_fields.Add(type, mapField);
}
this.m_types.Add(strtype, type);
return type;
}
private MethodInfo RegisterTemplate(DocTemplateDefinition dtd)
{
if (dtd == null || dtd.Rules == null)
return null;
MethodInfo methodexist = null;
if (this.m_templates.TryGetValue(dtd, out methodexist))
return methodexist;
Type[] paramtypes = null;
DocModelRule[] parameters = dtd.GetParameterRules();
if(parameters != null && parameters.Length > 0)
{
paramtypes = new Type[parameters.Length];
for(int iParam = 0; iParam < parameters.Length; iParam++)
{
DocModelRule param = parameters[iParam];
paramtypes[iParam] = RegisterType(param.Name);
}
}
TypeBuilder tb = (System.Reflection.Emit.TypeBuilder)this.RegisterType(dtd.Type);
string methodname = dtd.Name.Replace(' ', '_').Replace(':', '_').Replace('-', '_');
MethodBuilder method = tb.DefineMethod(methodname, MethodAttributes.Public, CallingConventions.HasThis, typeof(bool), paramtypes);
ILGenerator generator = method.GetILGenerator();
foreach (DocModelRule docRule in dtd.Rules)
{
docRule.EmitInstructions(this, generator, dtd);
}
// if made it to the end, then successful, so return true
generator.Emit(OpCodes.Ldc_I4_1);
generator.Emit(OpCodes.Ret);
return method;
}
}
}