-
Notifications
You must be signed in to change notification settings - Fork 8
/
CodeGenerator.dbl
2490 lines (2192 loc) · 126 KB
/
CodeGenerator.dbl
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
;;*****************************************************************************
;;
;; Title: CodeGenerator.dbl
;;
;; Type: Class
;;
;; Description: In-process callable interface to CodeGen
;;
;; Date:
;;
;; Author: Steve Ives, Synergex Professional Services Group
;; http://www.synergex.com
;;
;;*****************************************************************************
;;
;; Copyright (c) 2012, Synergex International, Inc.
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;; POSSIBILITY OF SUCH DAMAGE.
;;
;;*****************************************************************************
import CodeGen.Engine
import CodeGen.MethodCatalogAPI
import CodeGen.RepositoryAPI
import Microsoft.Win32
import Newtonsoft.Json
import Newtonsoft.Json.Serialization
import System
import System.Collections
import System.Collections.Generic
import System.Collections.ObjectModel
import System.IO
import System.Linq
import System.Reflection
import System.Text
.array 0
namespace CodeGen.Engine
.include "CODEGEN_SRC:codegen.def"
public sealed class CodeGenerator
private context, @CodeGenContext
private readonly originalRpsmain, String
private readonly originalRpstext, String
public method CodeGenerator
required in taskset, @CodeGenTaskSet
default in aContext, @CodeGenContext, ^null
proc
context = aContext ?? new CodeGenContext(taskset)
;;If we're in developer debug or verbose modes then display the heading
if (context.DeveloperDebugLoggingEnabled || (context.VerboseLoggingEnabled))
taskset.VerboseLog(String.Format("CodeGen {0}",CODEGEN_VERSION), true, false)
;;Remember the original repository that was set before we changed anything
originalRpsmain = Environment.GetEnvironmentVariable("RPSMFIL")
originalRpstext = Environment.GetEnvironmentVariable("RPSTFIL")
;;Set the main environment variables (CODEGEN_EXE, CODEGEN_TPLDIR, CODEGEN_OUTDIR, CODEGEN_AUTHOR and CODEGEN_COMPANY)
configureEnvironment()
;;Load Harmony Core extensions
loadHarmonyCoreExtensions(context)
;;Load other extensions
loadExtensions(context)
;;Report loaded extensions
if (context.DeveloperDebugLoggingEnabled)
reportLoadedExtensions()
endmethod
private method configureEnvironment, void
.include "CODEGEN_SRC:codegen.def"
proc
;;Explicitly set CODEGEN_EXE to the path containing this code (CodeGenEngine.dll).
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("CODEGEN_EXE",Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(^typeof(CodeGenerator)).Location),sts)
.else
Environment.SetEnvironmentVariable("CODEGEN_EXE",Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(^typeof(CodeGenerator)).Location))
.endc
;;Make the current version number available in the expander
context.Version = CODEGEN_VERSION
.ifndef D_NETSTANDARD
;;Is CODEGEN_TPLDIR already set in the environment?
data templateFolder = Environment.GetEnvironmentVariable("CODEGEN_TPLDIR")
if (String.IsNullOrWhiteSpace(templateFolder))
begin
;;No, look in the registry for the value set by InstallShield
templateFolder = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Synergex\CodeGen","TemplatePath","")
if (!String.IsNullOrWhiteSpace(templateFolder)) then
begin
;;Found it
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("CODEGEN_TPLDIR",templateFolder.Trim(),sts)
.else
Environment.SetEnvironmentVariable("CODEGEN_TPLDIR",templateFolder.Trim())
.endc
end
else if (Environment.Is64BitProcess)
begin
;;Not found. If we're a 64-bit process then try looking in the 32-bit registry
templateFolder = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Synergex\CodeGen","TemplatePath","")
if (!String.IsNullOrWhiteSpace(templateFolder))
begin
;;Found it
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("CODEGEN_TPLDIR",templateFolder.Trim(),sts)
.else
Environment.SetEnvironmentVariable("CODEGEN_TPLDIR",templateFolder.Trim())
.endc
end
end
end
.endc
;;Is CODEGEN_AUTHOR already set in the environment?
data authorName = Environment.GetEnvironmentVariable("CODEGEN_AUTHOR")
if (!String.IsNullOrWhiteSpace(authorName)) then
context.Author = authorName
else
begin
.ifndef D_NETSTANDARD
;;No, look in the registry for the value set by InstallShield
authorName = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Synergex\CodeGen","DefaultAuthor","")
if (!String.IsNullOrWhiteSpace(authorName)) then
context.Author = authorName
else if (Environment.Is64BitProcess)
begin
;;Not found. If we're a 64-bit process then try looking in the 32-bit registry
authorName = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Synergex\CodeGen","DefaultAuthor","")
if (!String.IsNullOrWhiteSpace(authorName))
context.Author = authorName
end
.endc
end
;;Is CODEGEN_COMPANY already set in the environment?
data companyName = Environment.GetEnvironmentVariable("CODEGEN_COMPANY")
if (!String.IsNullOrWhiteSpace(companyName)) then
context.Company = companyName
else
begin
.ifndef D_NETSTANDARD
;;No, look in the registry for the value set by InstallShield
companyName = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Synergex\CodeGen","DefaultCompany","")
if (!String.IsNullOrWhiteSpace(companyName)) then
context.Company = companyName
else if (Environment.Is64BitProcess)
begin
;;Not found. If we're a 64-bit process then try looking in the 32-bit registry
companyName = (String)Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Synergex\CodeGen","DefaultCompany","")
if (!String.IsNullOrWhiteSpace(companyName))
context.Company = companyName
end
.endc
end
endmethod
public static method LoadHarmonyCoreExtensions, void
required in context, @CodeGenContext
proc
context.Taskset.DevDebugLog("----------------------------------------------------------")
context.Taskset.DevDebugLog("HARMONY CORE EXTENSIONS")
;;Look for the extensions assembly in the same folder as CodeGen
data codeBaseUri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase)
data harmonyLocation = Path.GetDirectoryName(Uri.UnescapeDataString(codeBaseUri.Path))
data extensionsAssembly = Path.Combine(harmonyLocation,"HarmonyCoreExtensions.dll")
if (File.Exists(extensionsAssembly)) then
begin
;;Report the extensions assembly we're going to use
context.Taskset.DevDebugLog(String.Format("Found Harmony Core extensions assembly {0}",extensionsAssembly))
;;Open the assembly and load extensions
if (!loadExtensionsFromAssembly(extensionsAssembly,context))
context.Taskset.DevDebugLog("No extension classes were found in the extensions assembly!")
end
else
begin
context.Taskset.DevDebugLog("No Harmony Core extensions assembly was found!")
end
context.Taskset.DevDebugLog("Finished loading Harmony Core extensions.")
endmethod
public static method LoadExtensions, void
required in context, @CodeGenContext
proc
context.Taskset.DevDebugLog("----------------------------------------------------------")
context.Taskset.DevDebugLog("OTHER EXTENSIONS")
;;Do we have a CODEGEN_EXTDIR environment variable?
data location = Environment.GetEnvironmentVariable("CODEGEN_EXTDIR")
if (!string.IsNullOrWhiteSpace(location))
begin
if (!Directory.Exists(location))
begin
context.Taskset.DevDebugLog("Ignoring extensions location specified by CODEGEN_EXTDIR because the location does not exist")
location = String.Empty
end
end
if (String.IsNullOrWhiteSpace(location))
begin
;;No CODEGEN_EXTDIR so we'll use CODEGEN_EXE which is ALWAYS defined
location = Environment.GetEnvironmentVariable("CODEGEN_EXE")
end
context.Taskset.DevDebugLog("Searching for extensions in " + location)
data extensionAssembly, String
data extensionsFound = false
foreach extensionAssembly in Directory.GetFiles(location,"custom*.dll")
begin
if (loadExtensionsFromAssembly(extensionAssembly,context))
extensionsFound = true
end
if (!extensionsFound)
context.Taskset.DevDebugLog("No extensions found")
context.Taskset.DevDebugLog("Finished loading extensions")
endmethod
public static method LoadProformaExtensions, boolean
required in context, @CodeGenContext
proc
data errStatus = false
;;-------------------------------------------------------------------------
;;Do we have a custom assembly containing a BusinessCreft ProForma processor?
context.Taskset.DevDebugLog("Attempting to load BusinessCraft Proforma extensions")
;;Do we have a CODEGEN_EXTDIR environment variable?
data location = Environment.GetEnvironmentVariable("CODEGEN_EXTDIR")
if (String.IsNullOrWhiteSpace(location))
begin
;;No CODEGEN_EXTDIR so we'll use CODEGEN_EXE which is ALWAYS defined
location = Environment.GetEnvironmentVariable("CODEGEN_EXE")
end
;;Setup a file spec to locate custom token processor extensions
data extensionsAssembly = Path.Combine(location,"CodeGenProForma.dll")
;;Search for and open custom token processor extensions
if (!File.Exists(extensionsAssembly)) then
errStatus = context.Taskset.Errorlog(String.Format("Proforma assembly {0} not found!",extensionsAssembly))
else
begin
;;Open the assembly and load extensions
if (!loadExtensionsFromAssembly(extensionsAssembly,context))
errStatus = context.Taskset.ErrorLog("No extensions were found in the proforma extensions assembly!")
end
mreturn !errStatus
endmethod
private static method LoadExtensionsFromAssembly, boolean
required in extensionAssembly, string
required in context, @CodeGenContext
proc
data ok = true
data extensionsLoaded = 0
;;Open the assembly
data asm, @Assembly
try
begin
asm = Assembly.LoadFrom(extensionAssembly)
end
catch (e, @System.IO.FileLoadException)
begin
data messageToReport = (e.InnerException!=^null) ? e.InnerException.Message : e.Message
context.Taskset.Warning(String.Format("Failed to activate extensions assembly {0}. Error was: {1}.",Path.GetFileName(extensionAssembly),messageToReport))
ok = false
end
catch (e, @Exception)
begin
context.Taskset.Warning(String.Format("Failed to activate extensions assembly {0}. Error was: {1}.",Path.GetFileName(extensionAssembly),e.Message))
ok = false
end
endtry
if (ok)
begin
context.Taskset.DevDebugLog(String.Format("Opened assembly {0}",extensionAssembly))
;;Look through all the types in the assembly searching for types that implement
;;IExpansionToken or IExpressionToken and record them in the extension collections.
data discoveredType, @Type
data discoveredTypes, [#]@Type
try
begin
discoveredTypes = asm.GetTypes()
end
catch (ex, @ReflectionTypeLoadException)
begin
data sb = new StringBuilder()
data exSub, @Exception
foreach exSub in ex.LoaderExceptions
begin
sb.AppendLine(exSub.Message)
sb.AppendLine()
end
context.Taskset.Warning(String.Format("Failed to load extensions from assembly {0}. Error was {1}.",Path.GetFileName(extensionAssembly),sb.ToString()))
ok = false
end
endtry
if (!ok)
exit
foreach discoveredType in discoveredTypes
begin
data discoveredInterfaces, [#]@Type, discoveredType.GetInterfaces()
if (discoveredInterfaces.Length)
begin
;;The type we found implements at least one interface
data interfaceType, @Type
foreach interfaceType in discoveredInterfaces
begin
if (interfaceType==^typeof(IExpansionToken)&&(discoveredType.GetConstructor(Type.EmptyTypes)!=^null)) then
begin
data expander, @IExpansionToken, (@IExpansionToken)Activator.CreateInstance(discoveredType)
context.CustomTokenExpanders.Add(Tuple.Create(expander.TokenName,expander.Description,expander.Validity,expander.TokenCase,(@Func<Token, FileNode, IEnumerable<LoopNode>, String>)expander.Expand))
extensionsLoaded += 1
exitloop
end
else if (interfaceType==^typeof(IExpressionToken)&&(discoveredType.GetConstructor(Type.EmptyTypes)!=^null))
begin
data evaluator, @IExpressionToken, (@IExpressionToken)Activator.CreateInstance(discoveredType)
context.CustomExpressionEvaluators.Add(Tuple.Create(evaluator.TokenName,evaluator.Description,evaluator.Validity,(@Func<Token, FileNode, IEnumerable<LoopNode>, Boolean>)evaluator.Evaluate))
extensionsLoaded += 1
exitloop
end
end
end
end
end
mreturn (extensionsLoaded > 0)
endmethod
private method reportLoadedExtensions, void
proc
context.Taskset.DevDebugLog("----------------------------------------------------------")
context.Taskset.DevDebugLog("SUMMARY OF LOADED EXTENSIONS")
if (context.CustomTokenExpanders.Count>0) then
begin
context.Taskset.DevDebugLog(" - Custom tokens have been loaded:")
if (context.DeveloperDebugLoggingEnabled)
begin
data expander, @Tuple<String,String,TokenValidity,TokenCaseMode,Func<Token, FileNode, IEnumerable<LoopNode>, String>>
foreach expander in context.CustomTokenExpanders
context.Taskset.DevDebugLog(" <" + expander.Item1 + ">")
end
end
else
context.Taskset.DevDebugLog(" - No custom tokens have been loaded")
if (context.CustomExpressionEvaluators.Count>0) then
begin
context.Taskset.DevDebugLog(" - Custom expressions have been loaded:")
if (context.DeveloperDebugLoggingEnabled)
begin
data evaluator, @Tuple<String,String,TokenValidity,Func<Token, FileNode, IEnumerable<LoopNode>, Boolean>>
foreach evaluator in context.CustomExpressionEvaluators
context.Taskset.DevDebugLog(" <" + evaluator.Item1 + ">")
end
end
else
context.Taskset.DevDebugLog(" - No custom expressions have been loaded")
endmethod
private method loadMethodCatalog, boolean
proc
;; NOTE: We only get here if a method catalog XML file is specified in context.CurrentTask.MethodCatalogFile
;;--------------------------------------------------------------------------------------
;;Load the method catalog from the XML file
if (context.MethodCatalog != ^null && !String.IsNullOrWhiteSpace(context.MethodCatalogLastFile) && context.MethodCatalogLastFile == context.CurrentTask.MethodCatalogFile && !context.MethodCatalogCustomized) then
begin
;;We can use the same SMC that we used for the last task
end
else
begin
;;We need to load the method catalog from scratch
try
begin
context.MethodCatalog = new Smc(context.CurrentTask.MethodCatalogFile,context.CurrentTask.MethodCatalogExtensionsFile)
end
catch (ex, @Exception)
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Failed to load method catalog. {0}",ex.Message))
end
endtry
end
;;--------------------------------------------------------------------------------------
;;
if (!context.CurrentTask.MethodCatalogStructureMode)
begin
;;Are we processing a single interface?
if (!String.IsNullOrWhiteSpace(context.CurrentTask.MethodCatalogInterface))
begin
;;Make sure it exists in the catalog
data selectedInterface = context.MethodCatalog.Interfaces.FirstOrDefault(lambda(intf) {intf.Name.ToUpper()==context.CurrentTask.MethodCatalogInterface.ToUpper()})
if (selectedInterface == ^null)
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Interface {0} was not found in the method catalog!",context.CurrentTask.MethodCatalogInterface))
end
;;And remove all other interfaces
context.MethodCatalog.Interfaces.RemoveAll(lambda(intf) {intf!=selectedInterface})
context.MethodCatalogCustomized = true
end
end
;;--------------------------------------------------------------------------------------
;; Now the method catalog file is in context.MethodCatalogFile and if in structures mode
;; the context.MethodCatalogStructureMode property will be true.
if (context.CurrentTask.MethodCatalogStructureMode)
begin
;;If we have an interface name, make sure it exists in the catalog
if (!String.IsNullOrWhiteSpace(context.CurrentTask.MethodCatalogInterface))
begin
if (context.MethodCatalog.Interfaces.FirstOrDefault(lambda(i) {i.Name==context.CurrentTask.MethodCatalogInterface}) == ^null)
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Interface {0} was not found in the method catalog!",context.CurrentTask.MethodCatalogInterface))
end
end
if (context.MethodCatalog.Structures.Count == 0)
begin
mreturn context.CurrentTask.ErrorLog("Method catalog export file contains no structures!")
end
;; Are we processing the whole catalog?
if (String.IsNullOrWhiteSpace(context.CurrentTask.MethodCatalogInterface)) then
begin
;; Yes, process all structures in the catalog
data tmpstr, @RpsStructure
foreach tmpstr in context.MethodCatalog.Structures
begin
context.CurrentTask.Structures.Add(tmpstr.Name)
end
end
else
begin
;; No, we're processing a single interface.
;; Process only structures referenced by methods in that interface.
data iface, @SmcInterface, context.MethodCatalog.Interfaces.First(lambda(if) {if.Name==context.CurrentTask.MethodCatalogInterface})
data methodsWithStructParams = iface.Methods.Where(lambda(meth) { meth.Parameters.Any(lambda(parm) { parm.Type == ParameterType.Structure } ) } )
data meth, @SmcMethod
foreach meth in methodsWithStructParams
begin
data structParams = meth.Parameters.Where(lambda(parm) { parm.Type == ParameterType.Structure })
data parm, @SmcParameter
foreach parm in structParams
begin
context.CurrentTask.Structures.AddIfMissing(parm.StructureName)
end
end
;; Did we find any?
if (context.CurrentTask.Structures.Count == 0)
begin
context.CurrentTask.Log("INFO: Method catalog interface references no structures!")
mreturn true
end
end
end
;;--------------------------------------------------------------------------------------
;; This code was previously part of the -iloop command line option processing
if (context.CurrentTask.MethodCatalogInterfaces != ^null)
begin
data newInterfaceCollection = new List<SmcInterface>()
data interfaceToInclude, @SmcInterface
data candidateInterfaceName, string
foreach candidateInterfaceName in context.CurrentTask.MethodCatalogInterfaces
begin
interfaceToInclude = context.MethodCatalog.Interfaces.FirstOrDefault(lambda(iface) {iface.Name.ToUpper().Equals(candidateInterfaceName.ToUpper())})
if (interfaceToInclude != ^null) then
begin
newInterfaceCollection.Add(interfaceToInclude)
end
else
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Interface {0} was not found in the method catalog!",candidateInterfaceName))
end
end
context.MethodCatalog.Interfaces = newInterfaceCollection
context.MethodCatalogCustomized = true
end
;;--------------------------------------------------------------------------------------
;;This code was previously part of the -minclude command line option processing
if (context.CurrentTask.MethodCatalogIncludeMethods != ^null)
begin
if (context.CurrentTask.MethodCatalogStructureMode) then
begin
;;We're in -smcstrs mode, which also means we only have a single interface
;;Remove Structures NOT referenced by methods in MethodCatalogIncludeMethods
;;from context.CurrentTask.Structures
;Get a handle on the SMC interface being processed
data currentInterface = context.MethodCatalog.Interfaces.FirstOrDefault(lambda(iface) { iface.Name.ToUpper() == context.CurrentTask.MethodCatalogInterface.ToUpper() } )
;;Build a collection of structures to keep
data structuresToKeep = new List<string>()
data methodName, string
foreach methodName in context.CurrentTask.MethodCatalogIncludeMethods
begin
data methodObject = currentInterface.Methods.FirstOrDefault(lambda(meth) {meth.Name.ToUpper().Equals(methodName.ToUpper())})
if (methodObject != ^null) then
begin
;;Does the method have any structure parameters?
data structureParameters = methodObject.Parameters.Where(lambda(param) { param.Type == ParameterType.Structure } )
if (structureParameters != ^null)
begin
data paramObject, @SmcParameter
foreach paramObject in structureParameters
begin
;;If the structure name is not already in the list of structures to leep, then add it
structuresToKeep.AddIfMissing(paramObject.StructureName)
end
end
end
else
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Method {0} was not found in interface {1}!m",methodName,currentInterface.Name))
end
end
;;Replace the list of structures to be processed with the structures to keep
context.CurrentTask.Structures = new ObservableCollection<String>(structuresToKeep.ToArray())
end
else
begin
;;We're in -smc mode, filter methods to only those included in MethodCatalogIncludeMethods
data currentInterface = context.MethodCatalog.Interfaces.First()
data newMethodCollection = new List<SmcMethod>()
data candidateMethodName, string
foreach candidateMethodName in context.CurrentTask.MethodCatalogIncludeMethods
begin
data methodToInclude = currentInterface.Methods.FirstOrDefault(lambda(meth) {meth.Name.ToUpper().Equals(candidateMethodName.ToUpper())})
if (methodToInclude != ^null) then
begin
newMethodCollection.Add(methodToInclude)
end
else
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Method {0} was not found in interface {1}!",candidateMethodName,currentInterface.Name))
end
end
currentInterface.Methods = newMethodCollection
context.MethodCatalogCustomized = true
end
end
;;--------------------------------------------------------------------------------------
;;This code was previously part of the -mexclude command line option processing
if (context.CurrentTask.MethodCatalogExcludeMethods != ^null)
begin
;; EXCLUDING METHODS
if (context.CurrentTask.MethodCatalogStructureMode) then
begin
;; SMCSTRS MODE
;; Exclude structures ONLY referenced by methods in MethodCatalogExcludeMethods from context.CurrentTask.Structures
data structuresToMaybeRemove = new List<string>()
;;Find the structures referenced by the excluded methods
data iface, @SmcInterface, context.MethodCatalog.Interfaces.First(lambda(if) {if.Name.ToUpper()==context.CurrentTask.MethodCatalogInterface.ToUpper()})
data methName, string
foreach methName in context.CurrentTask.MethodCatalogExcludeMethods
begin
data methodObject = iface.Methods.FirstOrDefault(lambda(mth) { mth.Name.ToUpper() == methName.ToUpper() } )
data structureParameters = methodObject.Parameters.Where(lambda(param) { param.Type == ParameterType.Structure } )
if (structureParameters != ^null)
begin
data structureParameter, @SmcParameter
foreach structureParameter in structureParameters
begin
structuresToMaybeRemove.AddIfMissing(structureParameter.StructureName)
end
end
end
;;Exclude any that are referenced by remaining methods
data ix, int
for ix from structuresToMaybeRemove.Count-1 thru 0 by -1
begin
data candidateStructure = structuresToMaybeRemove[ix]
lambda findParameter(p)
begin
mreturn p.Type == ParameterType.Structure && p.StructureName == candidateStructure
end
lambda findMethods(m)
begin
mreturn (!context.CurrentTask.MethodCatalogExcludeMethods.Contains(m.Name)) && m.Parameters.Any(findParameter)
end
data methodsReferencingStructure = iface.Methods.Where(findMethods)
;Debugging code
if (methodsReferencingStructure!=^null)
begin
data tmpmth, @List<SmcMethod>, new List<SmcMethod>(methodsReferencingStructure.ToArray())
nop
end
;End of debugging code
if (methodsReferencingStructure==^null || methodsReferencingStructure.Count()==0)
begin
structuresToMaybeRemove.RemoveAt(ix)
end
end
;;Remove whatever remains from the list of structures to process
if (structuresToMaybeRemove.Count > 0)
begin
data structureToRemove, string
foreach structureToRemove in structuresToMaybeRemove
begin
context.CurrentTask.Structures.Remove(structureToRemove)
end
end
end
else
begin
;; SMC MODE
;; Exclude methods named in MethodCatalogExcludeMethods
data currentInterface = context.MethodCatalog.Interfaces.First()
data candidateMethodName, string
foreach candidateMethodName in context.CurrentTask.MethodCatalogExcludeMethods
begin
data methodToExclude = currentInterface.Methods.FirstOrDefault(lambda(meth) {meth.Name.ToUpper().Equals(candidateMethodName.ToUpper())})
if (methodToExclude != ^null) then
begin
currentInterface.Methods.Remove(methodToExclude)
context.MethodCatalogCustomized = true
end
else
begin
mreturn context.CurrentTask.ErrorLog(String.Format("Method {0} was not found in interface {1}!",candidateMethodName,currentInterface.Name))
end
end
end
end
;;--------------------------------------------------------------------------------------
;;Are we are bing asked to exclude certain parameters by name
if (context.CurrentTask.MethodCatalogExcludeParameters != ^null)
begin
data iface, @SmcInterface
foreach iface in context.MethodCatalog.Interfaces
begin
data meth, @SmcMethod
foreach meth in iface.Methods
begin
data paramsToKeep = new List<SmcParameter>()
data param, @SmcParameter
foreach param in meth.Parameters
begin
if (!context.CurrentTask.MethodCatalogExcludeParameters.Contains(param.Name,StringComparer.OrdinalIgnoreCase))
begin
paramsToKeep.Add(param)
end
end
if (paramsToKeep.Count != meth.Parameters.Count)
begin
meth.Parameters = paramsToKeep
context.MethodCatalogCustomized = true
end
end
end
end
;;--------------------------------------------------------------------------------------
;;Are we are bing asked to include certain parameters by name, excluding all others
if (context.CurrentTask.MethodCatalogIncludeParameters != ^null)
begin
data iface, @SmcInterface
foreach iface in context.MethodCatalog.Interfaces
begin
data meth, @SmcMethod
foreach meth in iface.Methods
begin
data paramsToKeep = new List<SmcParameter>()
data param, @SmcParameter
foreach param in meth.Parameters
begin
if (context.CurrentTask.MethodCatalogIncludeParameters.Contains(param.Name,StringComparer.OrdinalIgnoreCase))
begin
paramsToKeep.Add(param)
end
end
if (paramsToKeep.Count < meth.Parameters.Count)
begin
meth.Parameters = paramsToKeep
context.MethodCatalogCustomized = true
end
end
end
end
endmethod
;;; <summary>
;;; Generates code for all tasks in the current taskset.
;;; </summary>
;;; <returns>Returns true if code generation for all tasks completes successfully.</returns>
public method GenerateCode, Boolean
proc
data taskSetComplete = true
;;Make sure we have at least one task
if (context.Taskset.Tasks.Count == 0)
begin
context.Taskset.ErrorLog("Your CodeGen task set doesn't contain any tasks!")
context.Taskset.Complete = false
mreturn false
end
;;Raise the StartingTaskSet event
context.Taskset.RaiseStartingTaskSet()
;;Process each task
data task, @CodeGenTask
foreach task in context.Taskset.Tasks
begin
;;Reset the context for the new task and specify the current task
context.ResetTaskContext()
context.CurrentTask = task
;;Raise the TaskStarting event
task.RaiseStartingTask()
;;If this task defines a repository then use it. If not, and the task set has a repository, use that.
;;Otherwise, reset the repository to the way it was on entry
if (!String.IsNullOrWhiteSpace(task.RepositoryMainFile) && !String.IsNullOrWhiteSpace(task.RepositoryTextFile)) then
begin
if (context.DeveloperDebugLoggingEnabled)
begin
task.DevDebugLog("Repository set by TASK")
task.DevDebugLog(String.Format(" - Main file {0}",task.RepositoryMainFile))
task.DevDebugLog(String.Format(" - Text file {0}",task.RepositoryTextFile))
end
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("RPSMFIL",task.RepositoryMainFile,sts)
xcall setlog("RPSTFIL",task.RepositoryTextFile,sts)
.else
Environment.SetEnvironmentVariable("RPSMFIL",task.RepositoryMainFile)
Environment.SetEnvironmentVariable("RPSTFIL",task.RepositoryTextFile)
.endc
end
else if (!String.IsNullOrWhiteSpace(context.Taskset.RepositoryMainFile) && !String.IsNullOrWhiteSpace(context.Taskset.RepositoryTextFile)) then
begin
if (context.DeveloperDebugLoggingEnabled)
begin
task.DevDebugLog("Repository set by TASK SET")
task.DevDebugLog(String.Format(" - Main file {0}",context.Taskset.RepositoryMainFile))
task.DevDebugLog(String.Format(" - Text file {0}",context.Taskset.RepositoryTextFile))
end
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("RPSMFIL",context.Taskset.RepositoryMainFile,sts)
xcall setlog("RPSTFIL",context.Taskset.RepositoryTextFile,sts)
.else
Environment.SetEnvironmentVariable("RPSMFIL",context.Taskset.RepositoryMainFile)
Environment.SetEnvironmentVariable("RPSTFIL",context.Taskset.RepositoryTextFile)
.endc
end
else
begin
data mainFile = String.IsNullOrWhiteSpace(originalRpsmain) ? String.Empty : originalRpsmain
data textFile = String.IsNullOrWhiteSpace(originalRpstext) ? String.Empty : originalRpstext
if (context.DeveloperDebugLoggingEnabled)
begin
task.DevDebugLog("Repository NOT specified by TASK or TASK SET")
task.DevDebugLog(String.Format(" - Main file {0}",mainFile))
task.DevDebugLog(String.Format(" - Text file {0}",textFile))
end
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("RPSMFIL",mainFile,sts)
xcall setlog("RPSTFIL",textFile,sts)
.else
Environment.SetEnvironmentVariable("RPSMFIL",mainFile)
Environment.SetEnvironmentVariable("RPSTFIL",textFile)
.endc
end
;;Generate code
generateCodeForTask()
;;Record the final status of the task
task.Complete = (task.Errors == 0) && (task.Warnings == 0)
;;If the task failed, then so did the overall task set
if (!task.Complete)
taskSetComplete = false
;;Raise the TaskComplete event
task.RaiseTaskComplete()
end
;;Record if everything in the task set was completed successfully
context.Taskset.Complete = taskSetComplete
;;Raise the TaskSetComplete event
context.Taskset.RaiseTaskSetComplete()
mreturn context.Taskset.Complete
endmethod
;;;<summary>
;;;Generates code for a single task.
;;;</summary>
private method generateCodeForTask, void
proc
data errStatus = false
data structureWildcard = false
;;-------------------------------------------------------------------------
;;Echo command line?
if (context.Taskset.EchoCommands)
context.CurrentTask.EchoCommand()
;;-------------------------------------------------------------------------
;;Try to load the entire repository into the current task context
try
begin
context.Repository = new Repository()
if (context.DeveloperDebugLoggingEnabled)
begin
context.CurrentTask.DevDebugLog("Repository opened")
context.CurrentTask.DevDebugLog(String.Format(" - Main file {0}",context.Repository.MainFile))
context.CurrentTask.DevDebugLog(String.Format(" - Text file {0}",context.Repository.TextFile))
end
end
catch (ex, @RpsException)
begin
;;Failed to load a repository. If we're processing structures we're dead!
if (context.CurrentTask.Structures.Count > 0)
errStatus = context.CurrentTask.ErrorLog(ex.Message)
end
endtry
;;-------------------------------------------------------------------------
;;If we are doing method catalog processing, configure that environment
;;If we are in method catalog mode, load up the catalog
if (!errStatus && !String.IsNullOrWhiteSpace(context.CurrentTask.MethodCatalogFile))
errStatus = loadMethodCatalog()
;;-------------------------------------------------------------------------
;;Do we have a custom data mappings file specified?
if (!errStatus)
begin
if (!String.IsNullOrWhiteSpace(context.Taskset.DataMappingsFile))
begin
;;Expand any logical names that might be there
data mappingFile = context.taskset.DataMappingsFile
if (!FileTools.ExpandLogicalName(mappingFile)) then
errStatus = context.CurrentTask.ErrorLog(String.Format("Failed to translate logical names in data mappings file {0}",context.Taskset.DataMappingsFile))
else
begin
;;Make sure the file exists
if (!File.Exists(mappingFile)) then
errStatus = context.CurrentTask.Errorlog(string.Format("Failed to open custom data mappings file {0}", context.Taskset.DataMappingsFile))
else
begin
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("CODEGEN_DATAMAPPING_FILE",mappingFile,sts)
.else
Environment.SetEnvironmentVariable("CODEGEN_DATAMAPPING_FILE",mappingFile)
.endc
context.CurrentTask.DevDebugLog("Custom data mapping file set to " + mappingFile)
end
end
end
end
;;-------------------------------------------------------------------------
;;Tell Repositoiry API if we want to use a database other than SQL Server
if (!errStatus)
begin
if (context.Taskset.DatabaseType != SqlDatabaseType.SQLServer)
begin
.ifdef D_NETSTANDARD
;TODO: BUG: 4/12/2018 Using SetEnvironmentVariable seems to cause some issues in .NET Core
data sts, i4
xcall setlog("CODEGEN_DATABASE_TYPE",context.Taskset.DatabaseType.ToString(),sts)
.else
Environment.SetEnvironmentVariable("CODEGEN_DATABASE_TYPE",context.Taskset.DatabaseType.ToString())
.endc
end
end
;;-------------------------------------------------------------------------
;;Do we have a template folder specified via CODEGEN_TPLDIR: ? If so this overrides the default location of current directory.
if (!errStatus)
begin
data folder = Environment.GetEnvironmentVariable("CODEGEN_TPLDIR")
if (!String.IsNullOrWhiteSpace(folder))
begin
;;Make sure there is no whitespace
folder = folder.Trim()
;;Expand any logical names in the file spec.
if (!FileTools.ExpandLogicalName(folder)) then
errStatus = context.CurrentTask.ErrorLog(String.Format("Failed to expand logical name {0} in CODEGEN_TPLDIR:",folder))
else
begin
;;Make sure the folder ends with a path seperator
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
folder += Path.DirectorySeparatorChar
;;Make sure the folder exists.
if (!Directory.Exists(folder))
begin
;;CODEGEN_TPLDIR: is bad, but do we care?