-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathLibraryServices.cs
More file actions
1211 lines (1028 loc) · 48.7 KB
/
LibraryServices.cs
File metadata and controls
1211 lines (1028 loc) · 48.7 KB
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using Dynamo.Configuration;
using Dynamo.Core;
using Dynamo.Exceptions;
using Dynamo.Interfaces;
using Dynamo.Library;
using Dynamo.Logging;
using Dynamo.Utilities;
using ProtoCore;
using ProtoCore.AST.AssociativeAST;
using ProtoCore.BuildData;
using ProtoCore.CompilerDefinitions;
using ProtoCore.DSASM;
using ProtoCore.Namespace;
using ProtoCore.Utils;
using ProtoFFI;
using MethodAttributes = ProtoCore.AST.AssociativeAST.MethodAttributes;
using Operator = ProtoCore.DSASM.Operator;
namespace Dynamo.Engine
{
/// <summary>
/// LibraryServices is a singleton class which manages builtin libraries
/// as well as imported libraries. It is across different sessions.
/// </summary>
public class LibraryServices : LogSourceBase, IDisposable
{
private readonly Dictionary<string, FunctionGroup> builtinFunctionGroups =
new Dictionary<string, FunctionGroup>();
private readonly Dictionary<string, Dictionary<string, FunctionGroup>> importedFunctionGroups =
new Dictionary<string, Dictionary<string, FunctionGroup>>(new LibraryPathComparer());
// This list includes all preloaded libraries, packaged libraries, and zero-touch imported libraries
private readonly List<string> importedLibraries = new List<string>();
// This list includes all libraries loaded from package folders
private readonly List<string> packagedLibraries = new List<string>();
private readonly IPathManager pathManager;
private readonly IPreferences preferenceSettings;
/// <summary>
/// Returns core which is used for parsing code and loading libraries
/// </summary>
public ProtoCore.Core LibraryManagementCore { get; private set; }
private class UpgradeHint
{
public UpgradeHint()
{
UpgradeName = null;
AdditionalAttributes = new Dictionary<string, string>();
AdditionalElements = new List<XmlElement>();
}
// The new name of the method in Dynamo
public string UpgradeName { get; set; }
// A list of additional parameters to append or change on the XML node when migrating
public Dictionary<string, string> AdditionalAttributes { get; set; }
public List<XmlElement> AdditionalElements { get; set; }
}
private readonly Dictionary<string, UpgradeHint> priorNameHints =
new Dictionary<string, UpgradeHint>();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryServices"/> class.
/// </summary>
/// <param name="libraryManagementCore">Core which is used for parsing code and loading libraries</param>
/// <param name="pathManager">Instance of IPathManager containing neccessary Dynamo paths</param>
public LibraryServices(ProtoCore.Core libraryManagementCore, IPathManager pathManager)
: this(libraryManagementCore, pathManager, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="LibraryServices"/> class.
/// </summary>
/// <param name="libraryManagementCore">Core which is used for parsing code and loading libraries</param>
/// <param name="pathManager">Instance of IPathManager containing neccessary Dynamo paths</param>
/// <param name="preferences">The preference settings of the Dynamo instance</param>
public LibraryServices(ProtoCore.Core libraryManagementCore, IPathManager pathManager, IPreferences preferences)
{
LibraryManagementCore = libraryManagementCore;
this.pathManager = pathManager;
preferenceSettings = preferences;
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
PreloadLibraries(pathManager.PreloadedLibraries);
PopulateBuiltIns();
PopulateOperators();
PopulatePreloadLibraries();
LibraryLoadFailed += new EventHandler<LibraryLoadFailedEventArgs>(LibraryLoadFailureHandler);
}
private Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
var assemblyName = new AssemblyName(args.Name).Name + ".dll";
var assemblyPath = assemblyName;
try
{
if (pathManager.ResolveLibraryPath(ref assemblyPath))
{
return Dynamo.Utilities.AssemblyHelper.LoadInALCFrom(assemblyPath);
}
foreach (var packagesDirectory in pathManager.PackagesDirectories)
{
assemblyPath = Path.Combine(packagesDirectory, assemblyName);
if (File.Exists(assemblyPath))
return Dynamo.Utilities.AssemblyHelper.LoadInALCFrom(assemblyPath);
}
return null;
}
catch (Exception ex)
{
throw new Exception(string.Format("The location of the assembly, {0} could not be resolved for loading.", assemblyName), ex);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources
/// </summary>
public void Dispose()
{
builtinFunctionGroups.Clear();
importedFunctionGroups.Clear();
importedLibraries.Clear();
AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly;
}
internal PathManager PathManager => pathManager as PathManager;
/// <summary>
/// Returns a list of imported libraries.
/// </summary>
public IEnumerable<string> ImportedLibraries
{
get { return importedLibraries; }
}
/// <summary>
/// Returns built-in function groups.
/// </summary>
/// <returns></returns>
public IEnumerable<FunctionGroup> BuiltinFunctionGroups
{
get { return builtinFunctionGroups.Values; }
}
/// <summary>
/// Returns all imported function groups.
/// </summary>
public IEnumerable<FunctionGroup> ImportedFunctionGroups
{
get { return importedFunctionGroups.SelectMany(d => d.Value).Select(p => p.Value); }
}
/// <summary>
/// Occurs before a library is loaded
/// </summary>
public event EventHandler<LibraryLoadingEventArgs> LibraryLoading;
/// <summary>
/// Occurs if a library cannot be loaded
/// </summary>
public event EventHandler<LibraryLoadFailedEventArgs> LibraryLoadFailed;
/// <summary>
/// Occurs after a library is successfully loaded
/// </summary>
public event EventHandler<LibraryLoadedEventArgs> LibraryLoaded;
private void LibraryLoadFailureHandler(object sender, LibraryLoadFailedEventArgs args)
{
LibraryLoadFailedException ex = new LibraryLoadFailedException(args.LibraryPath, args.Reason);
Log(ex.Message, WarningLevel.Moderate);
Log(ex);
// NOTE: We do not want to throw an exception here if the failure was due
// to a missing library that was explicitly (attempted to be) loaded
// but was moved or deleted OR if a .DS file with syntax error(s) is loaded
if (args.ThrowOnFailure)
throw ex;
}
private void PreloadLibraries(IEnumerable<string> preloadLibraries)
{
importedLibraries.AddRange(preloadLibraries);
foreach (var library in importedLibraries)
CompilerUtils.TryLoadAssemblyIntoCore(LibraryManagementCore, library);
}
internal bool FunctionSignatureNeedsAdditionalAttributes(string functionSignature)
{
if (functionSignature == null)
{
return false;
}
if (!priorNameHints.ContainsKey(functionSignature))
return false;
return priorNameHints[functionSignature].AdditionalAttributes.Count > 0;
}
internal bool FunctionSignatureNeedsAdditionalElements(string functionSignature)
{
if (functionSignature == null)
{
return false;
}
if (!priorNameHints.ContainsKey(functionSignature))
return false;
return priorNameHints[functionSignature].AdditionalElements.Count > 0;
}
internal void AddAdditionalAttributesToNode(string functionSignature, XmlElement nodeElement)
{
var shortKey = GetQualifiedFunction(functionSignature);
if (!FunctionSignatureNeedsAdditionalAttributes(functionSignature)
&& !FunctionSignatureNeedsAdditionalAttributes(shortKey)) return;
var upgradeHint = FunctionSignatureNeedsAdditionalAttributes(functionSignature)
? priorNameHints[functionSignature]
: priorNameHints[shortKey];
foreach (string key in upgradeHint.AdditionalAttributes.Keys)
{
var val = nodeElement.Attributes[key];
if (val != null)
{
nodeElement.Attributes[key].Value = upgradeHint.AdditionalAttributes[key];
continue;
}
nodeElement.SetAttribute(key, upgradeHint.AdditionalAttributes[key]);
}
}
internal void AddAdditionalElementsToNode(string functionSignature, XmlElement nodeElement)
{
var shortKey = GetQualifiedFunction(functionSignature);
if (!FunctionSignatureNeedsAdditionalElements(functionSignature)
&& !FunctionSignatureNeedsAdditionalElements(shortKey)) return;
var upgradeHint = FunctionSignatureNeedsAdditionalElements(functionSignature)
? priorNameHints[functionSignature]
: priorNameHints[shortKey];
foreach (XmlElement elem in upgradeHint.AdditionalElements)
{
XmlNode newNode = nodeElement.OwnerDocument.ImportNode(elem, true);
nodeElement.AppendChild(newNode);
}
}
internal string NameFromFunctionSignature(string functionSignature)
{
string[] splitted = null;
string newName = null;
if (priorNameHints.ContainsKey(functionSignature))
{
var mappedSignature = priorNameHints[functionSignature].UpgradeName;
splitted = mappedSignature.Split('@');
if (splitted.Length < 1 || String.IsNullOrEmpty(splitted[0]))
return null;
newName = splitted[0];
}
else
{
splitted = functionSignature.Split('@');
if (splitted.Length < 1 || String.IsNullOrEmpty(splitted[0]))
return null;
string qualifiedFunction = splitted[0];
if (!priorNameHints.ContainsKey(qualifiedFunction))
return null;
newName = priorNameHints[qualifiedFunction].UpgradeName;
}
splitted = newName.Split('.');
// Case for BuitIn nodes, because they don't have namespace or class.
if (splitted.Length == 1)
return newName;
// Other nodes should have at least 2 parameters.
if (splitted.Length < 2)
return null;
return splitted[splitted.Length - 2] + "." + splitted[splitted.Length - 1];
}
internal string GetFunctionSignatureFromFunctionSignatureHint(string functionSignature)
{
// if the hint is explicit, we can simply return the mapped function
if (priorNameHints.ContainsKey(functionSignature))
return priorNameHints[functionSignature].UpgradeName;
// if the hint is not explicit, we try the function name without parameters
string[] splitted = functionSignature.Split('@');
if (splitted.Length < 2 || String.IsNullOrEmpty(splitted[0]) || String.IsNullOrEmpty(splitted[1]))
return null;
string qualifiedFunction = splitted[0];
if (!priorNameHints.ContainsKey(qualifiedFunction))
return null;
string newName = priorNameHints[qualifiedFunction].UpgradeName;
return newName + "@" + splitted[1];
}
private string GetQualifiedFunction(string functionSignature)
{
// get a short name representation of the function without parameters
string[] splitted = functionSignature.Split('@');
if (splitted.Length < 1 || String.IsNullOrEmpty(splitted[0]))
return null;
string qualifiedFunction = splitted[0];
if (!priorNameHints.ContainsKey(qualifiedFunction))
return null;
return qualifiedFunction;
}
/// <summary>
/// Returns function groups from an imported library.
/// </summary>
/// <param name="library">Library path</param>
/// <returns></returns>
internal IEnumerable<FunctionGroup> GetFunctionGroups(string library)
{
if (null == library)
throw new ArgumentNullException();
Dictionary<string, FunctionGroup> functionGroups;
if (!importedFunctionGroups.TryGetValue(library, out functionGroups))
{
// Return an empty list instead of 'null' as some of the caller may
// not have the opportunity to check against 'null' enumerator (for
// example, an inner iterator in a nested LINQ statement).
return new List<FunctionGroup>();
}
IEnumerable<FunctionGroup> result = functionGroups.Values;
// Skip namespaces specified in the preference settings
var settings = preferenceSettings as PreferenceSettings;
if (settings != null)
{
foreach (var nsp in settings.NamespacesToExcludeFromLibrary
.Where(x => x.StartsWith(library + ':')).Select(x => x.Split(':').LastOrDefault()))
{
result = result.Where(funcGroup => !funcGroup.QualifiedName.StartsWith(nsp));
}
}
return result;
}
/// <summary>
/// Returns all function groups.
/// </summary>
internal IEnumerable<FunctionGroup> GetAllFunctionGroups()
{
return BuiltinFunctionGroups.Union(ImportedLibraries.SelectMany(GetFunctionGroups));
}
/// <summary>
/// Returns function descriptor from the managled function name.
/// name.
/// </summary>
/// <param name="library">Library path</param>
/// <param name="mangledName">Mangled function name</param>
/// <returns></returns>
public FunctionDescriptor GetFunctionDescriptor(string library, string mangledName)
{
if (null == library || null == mangledName)
throw new ArgumentNullException();
Dictionary<string, FunctionGroup> groups;
if (importedFunctionGroups.TryGetValue(library, out groups))
{
FunctionGroup functionGroup;
string qualifiedName = mangledName.Split(new[] { '@' })[0];
if (TryGetFunctionGroup(groups, qualifiedName, out functionGroup))
return functionGroup.GetFunctionDescriptor(mangledName);
}
return null;
}
/// <summary>
/// Returns a dictionary of old names vs. new names for node migration
/// </summary>
/// <returns></returns>
public Dictionary<string, string> GetPriorNames()
{
var priorNames = new Dictionary<string, string>();
foreach (var kvp in priorNameHints)
{
priorNames[kvp.Key] = kvp.Value.UpgradeName;
}
return priorNames;
}
/// <summary>
/// Returns function descriptor from the managed function name.
/// </summary>
/// <param name="managledName"></param>
/// <returns></returns>
public FunctionDescriptor GetFunctionDescriptor(string managledName)
{
if (string.IsNullOrEmpty(managledName))
throw new ArgumentException("Invalid arguments");
string qualifiedName = managledName.Split(new[] { '@' })[0];
FunctionGroup functionGroup;
if (builtinFunctionGroups.TryGetValue(qualifiedName, out functionGroup))
return functionGroup.GetFunctionDescriptor(managledName);
return
importedFunctionGroups.Values.Any(
groupMap => TryGetFunctionGroup(groupMap, qualifiedName, out functionGroup))
? functionGroup.GetFunctionDescriptor(managledName)
: null;
}
/// <summary>
/// Returns a list of function descriptors associated with the function name.
/// </summary>
/// <param name="qualifiedName"></param>
/// <returns></returns>
public IEnumerable<FunctionDescriptor> GetAllFunctionDescriptors(string qualifiedName)
{
IEnumerable<FunctionDescriptor> descriptors = null;
FunctionGroup functionGroup;
// Check through both builtinFunctionGroups and importedFunctionGroups to find the function descriptors
if (builtinFunctionGroups.TryGetValue(qualifiedName, out functionGroup))
{
descriptors = functionGroup.Functions;
return descriptors;
}
foreach (var fg in importedFunctionGroups)
{
if (fg.Value.TryGetValue(qualifiedName, out functionGroup))
{
descriptors = functionGroup.Functions;
return descriptors;
}
}
return null; // If no function descriptors are found
}
/// <summary>
/// Checks if a given library is already loaded or not.
/// Only unique assembly names are allowed to be loaded
/// </summary>
/// <param name="library"> can be either the full path or the assembly name </param>
/// <returns> true even if the same library name is loaded from different paths </returns>
internal bool IsLibraryLoaded(string library)
{
return importedFunctionGroups.ContainsKey(library);
}
/// <summary>
/// Checks if a given function is in the builtinFunctionGroups so we do not necessarily look for it's library based on its Assembly tag
/// </summary>
/// <param name="library">assembly name</param>
/// <param name="name">name, used for searching as key with default value ""</param>
/// <returns></returns>
internal bool IsFunctionBuiltIn(string library, string name = "")
{
// For Nodes with not .dll specific Assembly tag
if (library == Categories.BuiltIn || library == Categories.Operators)
{
return builtinFunctionGroups.ContainsKey(name);
}
else
{
return false;
}
}
private static bool CanbeResolvedTo(ICollection<string> partialName, ICollection<string> fullName)
{
return null != partialName && null != fullName && partialName.Count <= fullName.Count
&& fullName.Reverse().Take(partialName.Count).SequenceEqual(partialName.Reverse());
}
private static bool TryGetFunctionGroup(
Dictionary<string, FunctionGroup> funcGroupMap, string qualifiedName, out FunctionGroup funcGroup)
{
if (funcGroupMap.TryGetValue(qualifiedName, out funcGroup))
return true;
string[] partialName = qualifiedName.Split('.');
string key = funcGroupMap.Keys.FirstOrDefault(k => CanbeResolvedTo(partialName, k.Split('.')));
if (key != null)
{
funcGroup = funcGroupMap[key];
return true;
}
return false;
}
/// <summary>
/// Import a library (if it hasn't been imported yet).
/// </summary>
/// <param name="library">The library to be loaded</param>
/// <param name="isExplicitlyImportedLib">Indicates if the library has been imported using the "File | ImportLibrary" command</param>
internal bool LoadNodeLibrary(string library, bool isExplicitlyImportedLib)
{
if (null == library)
throw new ArgumentNullException();
if (!library.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)
&& !library.EndsWith(".ds", StringComparison.InvariantCultureIgnoreCase))
{
string errorMessage = Properties.Resources.InvalidLibraryFormat;
OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
return false;
}
if (importedFunctionGroups.ContainsKey(library))
{
string errorMessage = string.Format(Properties.Resources.LibraryHasBeenLoaded, library);
OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
return false;
}
// Copy the library path so that the path can be reported in the case of a failure
// to resolve the library path. If there is a failure "library" is set to null.
string path = library;
if (!pathManager.ResolveLibraryPath(ref library))
{
string errorMessage = string.Format(Properties.Resources.LibraryPathCannotBeFound, path);
// In the case that a library was explicitly imported using the "File|Import Library" command
// set the load failed args to not throw an exception if the load fails. This can happen after using
// File|Import Library and then moving or deleting the library.
OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(path, errorMessage,
throwOnFailure: !isExplicitlyImportedLib));
return false;
}
OnLibraryLoading(new LibraryLoadingEventArgs(library));
try
{
DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
ProcedureTable functionTable = null;
int functionNumber = 0;
if (LibraryManagementCore.CodeBlockList.Any())
{
functionTable = LibraryManagementCore.CodeBlockList[0].procedureTable;
functionNumber = functionTable.Procedures.Count;
}
var classTable = LibraryManagementCore.ClassTable;
int classNumber = classTable.ClassNodes.Count;
CompilerUtils.TryLoadAssemblyIntoCore(LibraryManagementCore, library);
if(functionTable == null)
{
functionTable = LibraryManagementCore.CodeBlockList[0].procedureTable;
functionNumber = functionTable.Procedures.Count;
}
if (LibraryManagementCore.BuildStatus.ErrorCount > 0)
{
string errorMessage = string.Format(Properties.Resources.LibraryBuildError, library);
Log(errorMessage, WarningLevel.Moderate);
foreach (ErrorEntry error in LibraryManagementCore.BuildStatus.Errors)
{
Log(error.Message, WarningLevel.Moderate);
errorMessage += Environment.NewLine + error.Message;
}
throw new Exception(errorMessage);
}
LoadLibraryMigrations(library);
var loadedClasses = classTable.ClassNodes.Skip(classNumber);
foreach (var classNode in loadedClasses)
{
ImportClass(library, classNode);
}
var loadedFunctions = functionTable.Procedures.Skip(functionNumber);
foreach (var globalFunction in loadedFunctions)
{
ImportProcedure(library, globalFunction);
}
}
catch (DynamoServices.AssemblyBlockedException e)
{
// This exception is caught upstream after displaying a failed load library warning to the user.
throw e;
}
catch (Exception e)
{
OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, e.Message,
throwOnFailure: !isExplicitlyImportedLib));
return false;
}
if (!importedLibraries.Contains(library))
{
importedLibraries.Add(library);
}
return true;
}
internal void ImportLibrary(string library, bool isExplicitlyImportedLib = false)
{
LoadNodeLibrary(library, isExplicitlyImportedLib);
OnLibrariesImported(new LibraryLoadedEventArgs(new List<string> {library}));
}
internal void LoadLibraryMigrations(string library)
{
string fullLibraryName = library;
// If library is not found, that doesn't mean there is no migration file.
// E.g. built in nodes don't have assembly, but they do have migration file.
if (!pathManager.ResolveLibraryPath(ref fullLibraryName))
{
fullLibraryName = library;
}
string migrationsXMLFile = Path.Combine(Path.GetDirectoryName(fullLibraryName),
Path.GetFileNameWithoutExtension(fullLibraryName) + ".Migrations.xml");
if (!pathManager.ResolveDocumentPath(ref migrationsXMLFile))
return;
var foundPriorNameHints = new Dictionary<string, UpgradeHint>();
try
{
using (var reader = XmlReader.Create(migrationsXMLFile))
{
var doc = new XmlDocument();
doc.Load(reader);
XmlElement migrationsElement = doc.DocumentElement;
var names = new List<string>();
foreach (XmlNode subNode in migrationsElement.ChildNodes)
{
if (subNode.Name != "priorNameHint")
throw new Exception("Invalid XML");
names.Add(subNode.Name);
var upgradeHint = new UpgradeHint();
string oldName = null;
foreach (XmlNode hintSubNode in subNode.ChildNodes)
{
names.Add(hintSubNode.Name);
switch (hintSubNode.Name)
{
case "oldName":
oldName = hintSubNode.InnerText;
break;
case "newName":
upgradeHint.UpgradeName = hintSubNode.InnerText;
break;
case "additionalAttributes":
foreach (XmlNode attributesSubNode in hintSubNode.ChildNodes)
{
string attributeName = null;
string attributeValue = null;
switch (attributesSubNode.Name)
{
case "attribute":
foreach (XmlNode attributeSubNode in attributesSubNode.ChildNodes)
{
switch (attributeSubNode.Name)
{
case "name":
attributeName = attributeSubNode.InnerText;
break;
case "value":
attributeValue = attributeSubNode.InnerText;
break;
}
}
break;
}
upgradeHint.AdditionalAttributes[attributeName] = attributeValue;
}
break;
case "additionalElements":
foreach (XmlNode elementsSubnode in hintSubNode.ChildNodes)
{
XmlElement elem = elementsSubnode as XmlElement;
if (elem != null)
upgradeHint.AdditionalElements.Add(elem);
}
break;
}
}
foundPriorNameHints[oldName] = upgradeHint;
}
}
}
catch (Exception)
{
return; // if the XML file is badly formatted, return like it doesn't exist
}
// if everything parsed correctly, then add these names to the priorNameHints
foreach (string key in foundPriorNameHints.Keys)
{
priorNameHints[key] = foundPriorNameHints[key];
}
}
private void AddImportedFunctions(string library, IEnumerable<FunctionDescriptor> functions)
{
if (null == library || null == functions)
throw new ArgumentNullException();
Dictionary<string, FunctionGroup> fptrs;
if (!importedFunctionGroups.TryGetValue(library, out fptrs))
{
fptrs = new Dictionary<string, FunctionGroup>();
importedFunctionGroups[library] = fptrs;
}
foreach (FunctionDescriptor function in functions)
{
string qualifiedName = function.QualifiedName;
FunctionGroup functionGroup;
if (!fptrs.TryGetValue(qualifiedName, out functionGroup))
{
functionGroup = new FunctionGroup(qualifiedName);
fptrs[qualifiedName] = functionGroup;
}
functionGroup.AddFunctionDescriptor(function);
}
}
private void AddBuiltinFunctions(IEnumerable<FunctionDescriptor> functions)
{
if (null == functions)
throw new ArgumentNullException();
foreach (FunctionDescriptor function in functions)
{
string qualifiedName = function.QualifiedName;
if (CoreUtils.StartsWithDoubleUnderscores(qualifiedName))
continue;
FunctionGroup functionGroup;
if (!builtinFunctionGroups.TryGetValue(qualifiedName, out functionGroup))
{
functionGroup = new FunctionGroup(qualifiedName);
builtinFunctionGroups[qualifiedName] = functionGroup;
}
functionGroup.AddFunctionDescriptor(function);
}
}
/// <summary>
/// Add DesignScript builtin functions to the library.
/// </summary>
private void PopulateBuiltIns()
{
if (LibraryManagementCore == null)
return;
if (LibraryManagementCore.CodeBlockList.Count <= 0)
return;
var builtins = LibraryManagementCore.CodeBlockList[0]
.procedureTable
.Procedures
.Where(p =>
!p.Name.StartsWith(Constants.kInternalNamePrefix) &&
!p.Name.Equals("Break"));
IEnumerable<FunctionDescriptor> functions = from method in builtins
let arguments =
method.ArgumentInfos.Zip(
method.ArgumentTypes,
(arg, argType) =>
new TypedParameter(
arg.Name,
argType))
let visibleInLibrary =
(method.MethodAttribute == null || !method.MethodAttribute.HiddenInLibrary)
let obsoleteMsg =
(method.MethodAttribute != null ? method.MethodAttribute.ObsoleteMessage: String.Empty)
let description =
(method.MethodAttribute != null ? method.MethodAttribute.Description :String.Empty)
select
new FunctionDescriptor(new FunctionDescriptorParams
{
FunctionName = method.Name,
Summary = description,
Parameters = arguments,
PathManager = pathManager,
ReturnType = method.ReturnType,
FunctionType = FunctionType.GenericFunction,
IsVisibleInLibrary = visibleInLibrary,
IsBuiltIn = true,
IsPackageMember = false,
ObsoleteMsg = obsoleteMsg,
Assembly = Categories.BuiltIn
});
AddBuiltinFunctions(functions);
LoadLibraryMigrations(Categories.BuiltIn);
}
private static IEnumerable<TypedParameter> GetBinaryFuncArgs()
{
yield return new TypedParameter("x", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var));
yield return new TypedParameter("y", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var));
}
private static IEnumerable<TypedParameter> GetUnaryFuncArgs()
{
return new List<TypedParameter> { new TypedParameter("x", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var)), };
}
/// <summary>
/// Add operators to the library.
/// </summary>
private void PopulateOperators()
{
var args = GetBinaryFuncArgs();
var ops = new[]
{
Op.GetOpFunction(Operator.add), Op.GetOpFunction(Operator.sub), Op.GetOpFunction(Operator.mul),
Op.GetOpFunction(Operator.div), Op.GetOpFunction(Operator.eq), Op.GetOpFunction(Operator.ge),
Op.GetOpFunction(Operator.gt), Op.GetOpFunction(Operator.mod), Op.GetOpFunction(Operator.le),
Op.GetOpFunction(Operator.lt), Op.GetOpFunction(Operator.and), Op.GetOpFunction(Operator.or),
Op.GetOpFunction(Operator.nq),
};
var functions =
ops.Select(op => new FunctionDescriptor(new FunctionDescriptorParams
{
FunctionName = op,
Parameters = args,
PathManager = pathManager,
FunctionType = FunctionType.GenericFunction,
IsBuiltIn = true,
IsPackageMember = false,
Assembly = Categories.Operators
}))
.Concat(new FunctionDescriptor(new FunctionDescriptorParams
{
FunctionName = Op.GetUnaryOpFunction(UnaryOperator.Not),
Parameters = GetUnaryFuncArgs(),
PathManager = pathManager,
FunctionType = FunctionType.GenericFunction,
IsBuiltIn = true,
IsPackageMember = false,
Assembly = Categories.Operators
}).AsSingleton());
AddBuiltinFunctions(functions);
}
/// <summary>
/// Populate preloaded libraries.
/// </summary>
private void PopulatePreloadLibraries()
{
HashSet<String> librariesThatNeedMigrationLoading = new HashSet<string>();
foreach (ClassNode classNode in LibraryManagementCore.ClassTable.ClassNodes)
{
if (classNode.IsImportedClass && !string.IsNullOrEmpty(classNode.ExternLib))
{
string library = Path.GetFileName(classNode.ExternLib);
ImportClass(library, classNode);
librariesThatNeedMigrationLoading.Add(library);
}
}
foreach (String library in librariesThatNeedMigrationLoading)
{
LoadLibraryMigrations(library);
}
}
/// <summary>
/// Try get default argument expression from DefaultArgumentAttribute,
/// and parse into Associaitve AST node.
/// </summary>
/// <param name="arg"></param>
/// <param name="defaultArgumentNode"></param>
/// <returns></returns>
private bool TryGetDefaultArgumentFromAttribute(ArgumentInfo arg, out AssociativeNode defaultArgumentNode)
{
defaultArgumentNode = null;
if (arg.Attributes == null)
return false;
object o;
if (!arg.Attributes.TryGetAttribute("DefaultArgumentAttribute", out o))
return false;
var defaultExpression = o as string;
if (string.IsNullOrEmpty(defaultExpression))
return false;
defaultArgumentNode = ParserUtils.ParseRHSExpression(defaultExpression, LibraryManagementCore);
return defaultArgumentNode != null;
}
private void ImportProcedure(string library, ProcedureNode proc)
{
string procName = proc.Name;
if (proc.IsAutoGeneratedThisProc ||
// There could be DS functions that have private access
// that shouldn't be imported into the Library
proc.AccessModifier == AccessModifier.Private ||
CoreUtils.IsSetter(procName) ||
CoreUtils.IsDisposeMethod(procName) ||
CoreUtils.StartsWithDoubleUnderscores(procName))
{
return;
}
string obsoleteMessage = "";
int classScope = proc.ClassID;
string className = string.Empty;
MethodAttributes methodAttribute = proc.MethodAttribute;
ClassAttributes classAttribute = null;
if (classScope != Constants.kGlobalScope)
{
var classNode = LibraryManagementCore.ClassTable.ClassNodes[classScope];
classAttribute = classNode.ClassAttributes;
className = classNode.Name;
}
// MethodAttribute's HiddenInLibrary has higher priority than
// ClassAttribute's HiddenInLibrary
var isVisible = true;
var canUpdatePeriodically = false;
if (methodAttribute != null)
{
isVisible = !methodAttribute.HiddenInLibrary;
canUpdatePeriodically = methodAttribute.CanUpdatePeriodically;
}
else
{
if (classAttribute != null)