| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using Elsa.Dsl.ElsaScript.Ast; |
| | | 3 | | using Elsa.Dsl.ElsaScript.Contracts; |
| | | 4 | | using Elsa.Dsl.ElsaScript.Helpers; |
| | | 5 | | using Elsa.Expressions.Models; |
| | | 6 | | using Elsa.Workflows; |
| | | 7 | | using Elsa.Workflows.Activities; |
| | | 8 | | using Elsa.Workflows.Activities.Flowchart.Models; |
| | | 9 | | using Elsa.Workflows.Memory; |
| | | 10 | | using Elsa.Workflows.Models; |
| | | 11 | | |
| | | 12 | | namespace Elsa.Dsl.ElsaScript.Compiler; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Compiles an ElsaScript AST into Elsa workflows. |
| | | 16 | | /// </summary> |
| | 364 | 17 | | public class ElsaScriptCompiler(IActivityRegistryLookupService activityRegistryLookupService, IElsaScriptParser parser) |
| | | 18 | | { |
| | 1 | 19 | | private static readonly Dictionary<string, string> LanguageMappings = new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 20 | | { |
| | 1 | 21 | | ["js"] = "JavaScript", |
| | 1 | 22 | | ["cs"] = "CSharp", |
| | 1 | 23 | | ["py"] = "Python", |
| | 1 | 24 | | ["liquid"] = "Liquid" |
| | 1 | 25 | | }; |
| | | 26 | | |
| | 364 | 27 | | private string _defaultExpressionLanguage = "JavaScript"; |
| | 364 | 28 | | private readonly Dictionary<string, Variable> _variables = new(); |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public async Task<Workflow> CompileAsync(string source, CancellationToken cancellationToken = default) |
| | | 32 | | { |
| | 12 | 33 | | var programNode = parser.Parse(source); |
| | 12 | 34 | | return await CompileAsync(programNode, cancellationToken); |
| | 12 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <inheritdoc /> |
| | | 38 | | public async Task<Workflow> CompileAsync(ProgramNode programNode, CancellationToken cancellationToken = default) |
| | | 39 | | { |
| | | 40 | | // Get the single workflow (enforced by parser) |
| | 12 | 41 | | var workflowNode = programNode.Workflows.First(); |
| | | 42 | | |
| | | 43 | | // Merge global use statements with workflow-level ones |
| | | 44 | | // Create a temporary workflow node with merged use statements |
| | 12 | 45 | | var mergedWorkflowNode = new WorkflowNode |
| | 12 | 46 | | { |
| | 12 | 47 | | Id = workflowNode.Id, |
| | 12 | 48 | | Metadata = workflowNode.Metadata, |
| | 12 | 49 | | UseStatements = [..programNode.GlobalUseStatements, ..workflowNode.UseStatements], |
| | 12 | 50 | | Body = workflowNode.Body |
| | 12 | 51 | | }; |
| | | 52 | | |
| | 12 | 53 | | return await CompileWorkflowNodeAsync(mergedWorkflowNode, cancellationToken); |
| | 12 | 54 | | } |
| | | 55 | | |
| | | 56 | | private async Task<Workflow> CompileWorkflowNodeAsync(WorkflowNode workflowNode, CancellationToken cancellationToken |
| | | 57 | | { |
| | 12 | 58 | | _variables.Clear(); |
| | 12 | 59 | | _defaultExpressionLanguage = "JavaScript"; |
| | | 60 | | |
| | | 61 | | // Process use statements (workflow-level overrides global) |
| | 42 | 62 | | foreach (var useNode in workflowNode.UseStatements) |
| | | 63 | | { |
| | 9 | 64 | | if (useNode.Type == UseType.Expressions) |
| | | 65 | | { |
| | 7 | 66 | | _defaultExpressionLanguage = MapLanguageName(useNode.Value); |
| | | 67 | | } |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | // Compile body statements |
| | 12 | 71 | | var activities = new List<IActivity>(); |
| | 58 | 72 | | foreach (var statement in workflowNode.Body) |
| | | 73 | | { |
| | 17 | 74 | | var activity = await CompileStatementAsync(statement, cancellationToken); |
| | 17 | 75 | | if (activity != null) |
| | | 76 | | { |
| | 13 | 77 | | activities.Add(activity); |
| | | 78 | | } |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | // Create the root activity (Sequence containing all statements) |
| | 12 | 82 | | var root = activities.Count == 1 |
| | 12 | 83 | | ? activities[0] |
| | 12 | 84 | | : new Sequence |
| | 12 | 85 | | { |
| | 12 | 86 | | Activities = activities |
| | 12 | 87 | | }; |
| | | 88 | | |
| | | 89 | | // Extract metadata with defaults |
| | 12 | 90 | | var definitionId = GetMetadataValue<string>(workflowNode.Metadata, "DefinitionId") ?? workflowNode.Id; |
| | 12 | 91 | | var displayName = GetMetadataValue<string>(workflowNode.Metadata, "DisplayName") ?? workflowNode.Id; |
| | 12 | 92 | | var description = GetMetadataValue<string>(workflowNode.Metadata, "Description") ?? string.Empty; |
| | 12 | 93 | | var definitionVersionId = GetMetadataValue<string>(workflowNode.Metadata, "DefinitionVersionId") ?? $"{definitio |
| | 12 | 94 | | var version = GetMetadataValueOrDefault(workflowNode.Metadata, "Version", 1); |
| | 12 | 95 | | var usableAsActivity = GetMetadataValue<bool?>(workflowNode.Metadata, "UsableAsActivity"); |
| | | 96 | | |
| | | 97 | | // Create the workflow |
| | 12 | 98 | | var workflow = new Workflow |
| | 12 | 99 | | { |
| | 12 | 100 | | Name = displayName, |
| | 12 | 101 | | Identity = new WorkflowIdentity(definitionId, version, definitionVersionId, null), |
| | 12 | 102 | | WorkflowMetadata = new(displayName, description, ToolVersion: new("3.6.0")), |
| | 12 | 103 | | Root = root, |
| | 12 | 104 | | Variables = _variables.Values.ToList(), |
| | 12 | 105 | | Options = new() |
| | 12 | 106 | | { |
| | 12 | 107 | | UsableAsActivity = usableAsActivity |
| | 12 | 108 | | } |
| | 12 | 109 | | }; |
| | | 110 | | |
| | 12 | 111 | | return workflow; |
| | 12 | 112 | | } |
| | | 113 | | |
| | | 114 | | private T? GetMetadataValue<T>(Dictionary<string, object> metadata, string key) => |
| | 60 | 115 | | metadata.TryGetValue(key, out var value) ? ConvertValue<T>(value, default) : default; |
| | | 116 | | |
| | | 117 | | private T GetMetadataValueOrDefault<T>(Dictionary<string, object> metadata, string key, T defaultValue) => |
| | 12 | 118 | | metadata.TryGetValue(key, out var value) ? ConvertValue(value, defaultValue) ?? defaultValue : defaultValue; |
| | | 119 | | |
| | | 120 | | private static T? ConvertValue<T>(object value, T? defaultValue) |
| | | 121 | | { |
| | | 122 | | // Handle direct type match |
| | 6 | 123 | | if (value is T typedValue) |
| | 5 | 124 | | return typedValue; |
| | | 125 | | |
| | | 126 | | // Try to convert |
| | | 127 | | try |
| | | 128 | | { |
| | 1 | 129 | | var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); |
| | 1 | 130 | | return (T)Convert.ChangeType(value, targetType); |
| | | 131 | | } |
| | 0 | 132 | | catch (Exception) |
| | | 133 | | { |
| | | 134 | | // Return default value if conversion fails |
| | 0 | 135 | | return defaultValue; |
| | | 136 | | } |
| | 1 | 137 | | } |
| | | 138 | | |
| | | 139 | | private async Task<IActivity?> CompileStatementAsync(StatementNode statement, CancellationToken cancellationToken = |
| | | 140 | | { |
| | 24 | 141 | | return statement switch |
| | 24 | 142 | | { |
| | 4 | 143 | | VariableDeclarationNode varDecl => CompileVariableDeclaration(varDecl), |
| | 13 | 144 | | ActivityInvocationNode actInv => await CompileActivityInvocationAsync(actInv, cancellationToken), |
| | 1 | 145 | | BlockNode block => await CompileBlockAsync(block, cancellationToken), |
| | 0 | 146 | | IfNode ifNode => await CompileIfAsync(ifNode, cancellationToken), |
| | 0 | 147 | | ForEachNode forEach => await CompileForEachAsync(forEach, cancellationToken), |
| | 2 | 148 | | ForNode forNode => await CompileForAsync(forNode, cancellationToken), |
| | 0 | 149 | | WhileNode whileNode => await CompileWhileAsync(whileNode, cancellationToken), |
| | 0 | 150 | | SwitchNode switchNode => await CompileSwitchAsync(switchNode, cancellationToken), |
| | 3 | 151 | | FlowchartNode flowchart => await CompileFlowchartAsync(flowchart, cancellationToken), |
| | 1 | 152 | | ListenNode listen => await CompileListenAsync(listen, cancellationToken), |
| | 0 | 153 | | _ => throw new NotSupportedException($"Statement type {statement.GetType().Name} is not supported") |
| | 24 | 154 | | }; |
| | 24 | 155 | | } |
| | | 156 | | |
| | | 157 | | private IActivity? CompileVariableDeclaration(VariableDeclarationNode varDecl) |
| | | 158 | | { |
| | | 159 | | // Create and register the variable |
| | 4 | 160 | | var initialValue = varDecl.Value != null ? EvaluateConstantExpression(varDecl.Value) : null; |
| | 4 | 161 | | var variable = new Variable(varDecl.Name, initialValue); |
| | 4 | 162 | | _variables[varDecl.Name] = variable; |
| | | 163 | | |
| | | 164 | | // Variable declarations don't produce activities themselves |
| | 4 | 165 | | return null; |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | private async Task<IActivity> CompileActivityInvocationAsync(ActivityInvocationNode actInv, CancellationToken cancel |
| | | 169 | | { |
| | | 170 | | // Try to find the activity type by name - try several strategies |
| | 14 | 171 | | var activityDescriptor = await activityRegistryLookupService.FindAsync(actInv.ActivityName); |
| | | 172 | | |
| | | 173 | | // If not found, try with "Elsa." prefix |
| | 14 | 174 | | if (activityDescriptor == null) |
| | | 175 | | { |
| | 14 | 176 | | activityDescriptor = await activityRegistryLookupService.FindAsync($"Elsa.{actInv.ActivityName}"); |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | // If still not found, search by descriptor name |
| | 14 | 180 | | if (activityDescriptor == null) |
| | | 181 | | { |
| | 0 | 182 | | activityDescriptor = await activityRegistryLookupService.FindAsync(d => d.Name == actInv.ActivityName); |
| | | 183 | | } |
| | | 184 | | |
| | 14 | 185 | | if (activityDescriptor == null) |
| | | 186 | | { |
| | 0 | 187 | | throw new InvalidOperationException($"Activity '{actInv.ActivityName}' not found in registry"); |
| | | 188 | | } |
| | | 189 | | |
| | 14 | 190 | | var activityType = activityDescriptor.ClrType; |
| | | 191 | | |
| | | 192 | | // Separate named and positional arguments |
| | | 193 | | var namedArgs = actInv.Arguments.Where(a => a.Name != null).ToList(); |
| | | 194 | | var positionalArgs = actInv.Arguments.Where(a => a.Name == null).ToList(); |
| | | 195 | | |
| | | 196 | | IActivity activity; |
| | | 197 | | |
| | | 198 | | // If we have positional arguments, try to find a matching constructor |
| | 14 | 199 | | if (positionalArgs.Any()) |
| | | 200 | | { |
| | 12 | 201 | | activity = InstantiateActivityUsingConstructor(activityType, positionalArgs); |
| | | 202 | | } |
| | | 203 | | else |
| | | 204 | | { |
| | | 205 | | // No positional arguments, use default constructor |
| | | 206 | | var activityConstructorContext = new ActivityConstructorContext(activityDescriptor, (t) => new(ActivityActiv |
| | 2 | 207 | | var activityConstructionResult = activityDescriptor.Constructor(activityConstructorContext); |
| | 2 | 208 | | activity = activityConstructionResult.Activity; |
| | | 209 | | } |
| | | 210 | | |
| | | 211 | | // Set named argument properties |
| | 28 | 212 | | foreach (var arg in namedArgs) |
| | | 213 | | { |
| | 0 | 214 | | var property = activityType.GetProperty(arg.Name!); |
| | | 215 | | |
| | 0 | 216 | | if (property != null) |
| | | 217 | | { |
| | 0 | 218 | | var value = CompileExpression(arg.Value, property.PropertyType); |
| | 0 | 219 | | property.SetValue(activity, value); |
| | | 220 | | } |
| | | 221 | | else |
| | | 222 | | { |
| | 0 | 223 | | throw new InvalidOperationException($"Property '{arg.Name}' not found on activity type '{activityType.Na |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | 14 | 227 | | return activity; |
| | 14 | 228 | | } |
| | | 229 | | |
| | | 230 | | private async Task<IActivity> CompileBlockAsync(BlockNode block, CancellationToken cancellationToken = default) |
| | | 231 | | { |
| | 1 | 232 | | var activities = new List<IActivity>(); |
| | | 233 | | |
| | 6 | 234 | | foreach (var statement in block.Statements) |
| | | 235 | | { |
| | 2 | 236 | | var activity = await CompileStatementAsync(statement, cancellationToken); |
| | 2 | 237 | | if (activity != null) |
| | | 238 | | { |
| | 2 | 239 | | activities.Add(activity); |
| | | 240 | | } |
| | | 241 | | } |
| | | 242 | | |
| | 1 | 243 | | return new Sequence |
| | 1 | 244 | | { |
| | 1 | 245 | | Activities = activities |
| | 1 | 246 | | }; |
| | 1 | 247 | | } |
| | | 248 | | |
| | | 249 | | private async Task<IActivity> CompileIfAsync(IfNode ifNode, CancellationToken cancellationToken = default) |
| | | 250 | | { |
| | 0 | 251 | | var condition = CompileExpressionAsInput<bool>(ifNode.Condition); |
| | 0 | 252 | | var thenActivity = await CompileStatementAsync(ifNode.Then, cancellationToken); |
| | 0 | 253 | | var elseActivity = ifNode.Else != null ? await CompileStatementAsync(ifNode.Else, cancellationToken) : null; |
| | | 254 | | |
| | 0 | 255 | | return new If(condition) |
| | 0 | 256 | | { |
| | 0 | 257 | | Then = thenActivity, |
| | 0 | 258 | | Else = elseActivity |
| | 0 | 259 | | }; |
| | 0 | 260 | | } |
| | | 261 | | |
| | | 262 | | private async Task<IActivity> CompileForEachAsync(ForEachNode forEach, CancellationToken cancellationToken = default |
| | | 263 | | { |
| | | 264 | | Variable loopVariable; |
| | | 265 | | |
| | 0 | 266 | | if (forEach.DeclaresVariable) |
| | | 267 | | { |
| | | 268 | | // Create a new loop variable |
| | 0 | 269 | | loopVariable = new Variable<object>(forEach.VariableName, null!); |
| | 0 | 270 | | _variables[forEach.VariableName] = loopVariable; |
| | | 271 | | } |
| | | 272 | | else |
| | | 273 | | { |
| | | 274 | | // Reuse existing variable |
| | 0 | 275 | | if (!_variables.TryGetValue(forEach.VariableName, out loopVariable!)) |
| | | 276 | | { |
| | 0 | 277 | | throw new InvalidOperationException($"Variable '{forEach.VariableName}' is not declared. Use 'var {forEa |
| | | 278 | | } |
| | | 279 | | } |
| | | 280 | | |
| | 0 | 281 | | var items = CompileExpressionAsInput<ICollection<object>>(forEach.Collection); |
| | 0 | 282 | | var body = await CompileStatementAsync(forEach.Body, cancellationToken); |
| | | 283 | | |
| | 0 | 284 | | var forEachActivity = new ForEach<object>(items) |
| | 0 | 285 | | { |
| | 0 | 286 | | CurrentValue = new(loopVariable), |
| | 0 | 287 | | Body = body |
| | 0 | 288 | | }; |
| | | 289 | | |
| | 0 | 290 | | return forEachActivity; |
| | 0 | 291 | | } |
| | | 292 | | |
| | | 293 | | private async Task<IActivity> CompileForAsync(ForNode forNode, CancellationToken cancellationToken = default) |
| | | 294 | | { |
| | | 295 | | Variable loopVariable; |
| | | 296 | | |
| | 2 | 297 | | if (forNode.DeclaresVariable) |
| | | 298 | | { |
| | | 299 | | // Create a new loop variable |
| | 2 | 300 | | loopVariable = new Variable<int>(forNode.VariableName, 0); |
| | 2 | 301 | | _variables[forNode.VariableName] = loopVariable; |
| | | 302 | | } |
| | | 303 | | else |
| | | 304 | | { |
| | | 305 | | // Reuse existing variable |
| | 0 | 306 | | if (!_variables.TryGetValue(forNode.VariableName, out loopVariable!)) |
| | | 307 | | { |
| | 0 | 308 | | throw new InvalidOperationException($"Variable '{forNode.VariableName}' is not declared. Use 'var {forNo |
| | | 309 | | } |
| | | 310 | | } |
| | | 311 | | |
| | 2 | 312 | | var start = CompileExpressionAsInput<int>(forNode.Start); |
| | 2 | 313 | | var end = CompileExpressionAsInput<int>(forNode.End); |
| | 2 | 314 | | var step = CompileExpressionAsInput<int>(forNode.Step); |
| | 2 | 315 | | var body = await CompileStatementAsync(forNode.Body, cancellationToken); |
| | | 316 | | |
| | 2 | 317 | | var forActivity = new For |
| | 2 | 318 | | { |
| | 2 | 319 | | Start = start, |
| | 2 | 320 | | End = end, |
| | 2 | 321 | | Step = step, |
| | 2 | 322 | | OuterBoundInclusive = new Input<bool>(forNode.IsInclusive), |
| | 2 | 323 | | CurrentValue = new Output<object?>(loopVariable), |
| | 2 | 324 | | Body = body |
| | 2 | 325 | | }; |
| | | 326 | | |
| | 2 | 327 | | return forActivity; |
| | 2 | 328 | | } |
| | | 329 | | |
| | | 330 | | private async Task<IActivity> CompileWhileAsync(WhileNode whileNode, CancellationToken cancellationToken = default) |
| | | 331 | | { |
| | 0 | 332 | | var condition = CompileExpressionAsInput<bool>(whileNode.Condition); |
| | 0 | 333 | | var body = await CompileStatementAsync(whileNode.Body, cancellationToken); |
| | | 334 | | |
| | 0 | 335 | | return new While(condition) |
| | 0 | 336 | | { |
| | 0 | 337 | | Body = body |
| | 0 | 338 | | }; |
| | 0 | 339 | | } |
| | | 340 | | |
| | | 341 | | private async Task<IActivity> CompileSwitchAsync(SwitchNode switchNode, CancellationToken cancellationToken = defaul |
| | | 342 | | { |
| | 0 | 343 | | var cases = new List<SwitchCase>(); |
| | | 344 | | |
| | 0 | 345 | | foreach (var caseNode in switchNode.Cases) |
| | | 346 | | { |
| | 0 | 347 | | var caseExpression = CompileExpressionAsExpression(caseNode.Value); |
| | 0 | 348 | | var caseBody = await CompileStatementAsync(caseNode.Body, cancellationToken); |
| | 0 | 349 | | cases.Add(new("Case", caseExpression, caseBody!)); |
| | 0 | 350 | | } |
| | | 351 | | |
| | 0 | 352 | | var defaultActivity = switchNode.Default != null ? await CompileStatementAsync(switchNode.Default, cancellationT |
| | | 353 | | |
| | 0 | 354 | | return new Switch |
| | 0 | 355 | | { |
| | 0 | 356 | | Cases = cases, |
| | 0 | 357 | | Default = defaultActivity |
| | 0 | 358 | | }; |
| | 0 | 359 | | } |
| | | 360 | | |
| | | 361 | | private async Task<IActivity> CompileFlowchartAsync(FlowchartNode flowchart, CancellationToken cancellationToken = d |
| | | 362 | | { |
| | | 363 | | // Register flowchart-scoped variables |
| | 6 | 364 | | foreach (var varDecl in flowchart.Variables) |
| | | 365 | | { |
| | 0 | 366 | | CompileVariableDeclaration(varDecl); |
| | | 367 | | } |
| | | 368 | | |
| | | 369 | | // Compile all labeled activities and build a label-to-activity map |
| | 3 | 370 | | var labelToActivity = new Dictionary<string, IActivity>(); |
| | 12 | 371 | | foreach (var labeledNode in flowchart.Activities) |
| | | 372 | | { |
| | 3 | 373 | | var activity = await CompileStatementAsync(labeledNode.Activity, cancellationToken); |
| | 3 | 374 | | if (activity != null) |
| | | 375 | | { |
| | 3 | 376 | | labelToActivity[labeledNode.Label] = activity; |
| | | 377 | | } |
| | 3 | 378 | | } |
| | | 379 | | |
| | | 380 | | // Create connections |
| | 3 | 381 | | var connections = new List<Connection>(); |
| | 8 | 382 | | foreach (var connNode in flowchart.Connections) |
| | | 383 | | { |
| | 1 | 384 | | if (!labelToActivity.TryGetValue(connNode.Source, out var sourceActivity)) |
| | 0 | 385 | | throw new InvalidOperationException($"Source label '{connNode.Source}' not found in flowchart"); |
| | | 386 | | |
| | 1 | 387 | | if (!labelToActivity.TryGetValue(connNode.Target, out var targetActivity)) |
| | 0 | 388 | | throw new InvalidOperationException($"Target label '{connNode.Target}' not found in flowchart"); |
| | | 389 | | |
| | 1 | 390 | | var source = new Endpoint(sourceActivity, connNode.Outcome); |
| | 1 | 391 | | var target = new Endpoint(targetActivity); |
| | 1 | 392 | | connections.Add(new Connection(source, target)); |
| | | 393 | | } |
| | | 394 | | |
| | | 395 | | // Create flowchart activity |
| | 3 | 396 | | var flowchartActivity = new Workflows.Activities.Flowchart.Activities.Flowchart |
| | 3 | 397 | | { |
| | 3 | 398 | | Activities = labelToActivity.Values.ToList(), |
| | 3 | 399 | | Connections = connections |
| | 3 | 400 | | }; |
| | | 401 | | |
| | | 402 | | // Set entry point if specified |
| | 3 | 403 | | if (!string.IsNullOrEmpty(flowchart.EntryPoint)) |
| | | 404 | | { |
| | 2 | 405 | | if (!labelToActivity.TryGetValue(flowchart.EntryPoint, out var startActivity)) |
| | 0 | 406 | | throw new InvalidOperationException($"Entry point label '{flowchart.EntryPoint}' not found in flowchart" |
| | | 407 | | |
| | 2 | 408 | | flowchartActivity.Start = startActivity; |
| | | 409 | | } |
| | | 410 | | |
| | 3 | 411 | | return flowchartActivity; |
| | 3 | 412 | | } |
| | | 413 | | |
| | | 414 | | private async Task<IActivity> CompileListenAsync(ListenNode listen, CancellationToken cancellationToken = default) |
| | | 415 | | { |
| | | 416 | | // Listen is just a regular activity invocation that can start a workflow |
| | 1 | 417 | | var activity = await CompileActivityInvocationAsync(listen.Activity, cancellationToken); |
| | | 418 | | |
| | | 419 | | // Try to set CanStartWorkflow if the activity supports it |
| | 1 | 420 | | var canStartWorkflowProp = activity.GetType().GetProperty("CanStartWorkflow"); |
| | 1 | 421 | | if (canStartWorkflowProp != null && canStartWorkflowProp.PropertyType == typeof(bool)) |
| | | 422 | | { |
| | 1 | 423 | | canStartWorkflowProp.SetValue(activity, true); |
| | | 424 | | } |
| | | 425 | | |
| | 1 | 426 | | return activity; |
| | 1 | 427 | | } |
| | | 428 | | |
| | | 429 | | private Input<T> CompileExpressionAsInput<T>(ExpressionNode exprNode) |
| | | 430 | | { |
| | 18 | 431 | | if (exprNode is LiteralNode literal) |
| | | 432 | | { |
| | 12 | 433 | | return new(new Literal(literal.Value!)); |
| | | 434 | | } |
| | | 435 | | |
| | 6 | 436 | | if (exprNode is IdentifierNode identifier) |
| | | 437 | | { |
| | | 438 | | // Reference to a variable |
| | 1 | 439 | | if (_variables.TryGetValue(identifier.Name, out var variable)) |
| | | 440 | | { |
| | 1 | 441 | | return new(variable); |
| | | 442 | | } |
| | | 443 | | |
| | | 444 | | // If not found, treat as a literal |
| | 0 | 445 | | return new(new Literal<T>(default!)); |
| | | 446 | | } |
| | | 447 | | |
| | 5 | 448 | | if (exprNode is ElsaExpressionNode elsaExpr) |
| | | 449 | | { |
| | 5 | 450 | | var language = elsaExpr.Language != null ? MapLanguageName(elsaExpr.Language) : _defaultExpressionLanguage; |
| | 5 | 451 | | var expression = new Expression(language, elsaExpr.Expression); |
| | 5 | 452 | | return new(expression); |
| | | 453 | | } |
| | | 454 | | |
| | 0 | 455 | | if (exprNode is ArrayLiteralNode arrayLiteral) |
| | | 456 | | { |
| | | 457 | | // For array literals, evaluate to a constant array if all elements are literals |
| | 0 | 458 | | var elements = arrayLiteral.Elements.Select(EvaluateConstantExpression).ToArray(); |
| | 0 | 459 | | return new((T)(object)elements); |
| | | 460 | | } |
| | | 461 | | |
| | 0 | 462 | | throw new NotSupportedException($"Expression type {exprNode.GetType().Name} is not supported"); |
| | | 463 | | } |
| | | 464 | | |
| | | 465 | | private Expression CompileExpressionAsExpression(ExpressionNode exprNode) |
| | | 466 | | { |
| | 0 | 467 | | if (exprNode is LiteralNode literal) |
| | | 468 | | { |
| | 0 | 469 | | return Expression.LiteralExpression(literal.Value); |
| | | 470 | | } |
| | | 471 | | |
| | 0 | 472 | | if (exprNode is ElsaExpressionNode elsaExpr) |
| | | 473 | | { |
| | 0 | 474 | | var language = elsaExpr.Language != null ? MapLanguageName(elsaExpr.Language) : _defaultExpressionLanguage; |
| | 0 | 475 | | return new(language, elsaExpr.Expression); |
| | | 476 | | } |
| | | 477 | | |
| | 0 | 478 | | throw new NotSupportedException($"Expression type {exprNode.GetType().Name} is not supported as Expression"); |
| | | 479 | | } |
| | | 480 | | |
| | | 481 | | [UnconditionalSuppressMessage("Trimming", "IL2060:Call to MakeGenericMethod can not be statically analyzed", Justifi |
| | | 482 | | private object CompileExpression(ExpressionNode exprNode, Type targetType) |
| | | 483 | | { |
| | | 484 | | // Check if targetType is already Input<T> |
| | | 485 | | Type innerType; |
| | 12 | 486 | | if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Input<>)) |
| | | 487 | | { |
| | | 488 | | // Extract the T from Input<T> |
| | 12 | 489 | | innerType = targetType.GetGenericArguments()[0]; |
| | | 490 | | } |
| | | 491 | | else |
| | | 492 | | { |
| | 0 | 493 | | innerType = targetType; |
| | | 494 | | } |
| | | 495 | | |
| | | 496 | | // Use reflection to call CompileExpressionAsInput<T> |
| | 12 | 497 | | var method = GetType().GetMethod(nameof(CompileExpressionAsInput), |
| | 12 | 498 | | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); |
| | 12 | 499 | | var genericMethod = method!.MakeGenericMethod(innerType); |
| | | 500 | | |
| | 12 | 501 | | return genericMethod.Invoke(this, [exprNode])!; |
| | | 502 | | } |
| | | 503 | | |
| | | 504 | | private object? EvaluateConstantExpression(ExpressionNode exprNode) |
| | | 505 | | { |
| | 4 | 506 | | if (exprNode is LiteralNode literal) |
| | | 507 | | { |
| | 4 | 508 | | return literal.Value; |
| | | 509 | | } |
| | | 510 | | |
| | 0 | 511 | | if (exprNode is ArrayLiteralNode arrayLiteral) |
| | | 512 | | { |
| | 0 | 513 | | return arrayLiteral.Elements.Select(EvaluateConstantExpression).ToArray(); |
| | | 514 | | } |
| | | 515 | | |
| | | 516 | | // For non-constant expressions, return null |
| | 0 | 517 | | return null; |
| | | 518 | | } |
| | | 519 | | |
| | | 520 | | private IActivity InstantiateActivityUsingConstructor(Type activityType, List<ArgumentNode> positionalArgs) |
| | | 521 | | { |
| | | 522 | | // Get all public constructors |
| | 12 | 523 | | var constructors = activityType.GetConstructors(System.Reflection.BindingFlags.Public | System.Reflection.Bindin |
| | | 524 | | |
| | | 525 | | // Filter constructors that: |
| | | 526 | | // 1. Have the same number of required Input<T> parameters as positional arguments (excluding optional params) |
| | | 527 | | // 2. All non-optional parameters are Input<T> types |
| | 12 | 528 | | var matchingConstructors = new List<(System.Reflection.ConstructorInfo ctor, System.Reflection.ParameterInfo[] i |
| | | 529 | | |
| | 176 | 530 | | foreach (var ctor in constructors) |
| | | 531 | | { |
| | 76 | 532 | | var parameters = ctor.GetParameters(); |
| | | 533 | | |
| | | 534 | | // Filter to only Input<T> parameters that are not optional (don't have default values or CallerMemberName a |
| | 76 | 535 | | var inputParams = parameters.Where(p => |
| | 228 | 536 | | p.ParameterType.IsGenericType && |
| | 228 | 537 | | p.ParameterType.GetGenericTypeDefinition() == typeof(Input<>) && |
| | 228 | 538 | | !p.IsOptional && |
| | 228 | 539 | | !p.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CallerFilePathAttribute), false).Any() && |
| | 228 | 540 | | !p.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CallerLineNumberAttribute), false).Any() & |
| | 228 | 541 | | !p.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CallerMemberNameAttribute), false).Any() |
| | 76 | 542 | | ).ToArray(); |
| | | 543 | | |
| | | 544 | | // Check if the number of required Input<T> params matches our positional args |
| | 76 | 545 | | if (inputParams.Length == positionalArgs.Count) |
| | | 546 | | { |
| | 12 | 547 | | matchingConstructors.Add((ctor, inputParams)); |
| | | 548 | | } |
| | | 549 | | } |
| | | 550 | | |
| | 12 | 551 | | if (!matchingConstructors.Any()) |
| | | 552 | | { |
| | 0 | 553 | | throw new InvalidOperationException( |
| | 0 | 554 | | $"No matching constructor found for activity type '{activityType.Name}' with {positionalArgs.Count} posi |
| | 0 | 555 | | $"Constructors must have Input<T> parameters matching the number of positional arguments."); |
| | | 556 | | } |
| | | 557 | | |
| | 12 | 558 | | if (matchingConstructors.Count > 1) |
| | | 559 | | { |
| | 0 | 560 | | throw new InvalidOperationException( |
| | 0 | 561 | | $"Multiple matching constructors found for activity type '{activityType.Name}' with {positionalArgs.Coun |
| | 0 | 562 | | $"Please use named arguments to disambiguate."); |
| | | 563 | | } |
| | | 564 | | |
| | 12 | 565 | | var (selectedCtor, selectedInputParams) = matchingConstructors[0]; |
| | | 566 | | |
| | | 567 | | // Build the constructor arguments |
| | 12 | 568 | | var ctorArgs = new List<object?>(); |
| | 12 | 569 | | var allParams = selectedCtor.GetParameters(); |
| | | 570 | | |
| | 96 | 571 | | foreach (var param in allParams) |
| | | 572 | | { |
| | | 573 | | // Check if this is one of our Input<T> parameters |
| | 36 | 574 | | var inputParamIndex = Array.IndexOf(selectedInputParams, param); |
| | | 575 | | |
| | 36 | 576 | | if (inputParamIndex >= 0) |
| | | 577 | | { |
| | | 578 | | // This is an Input<T> parameter - compile the corresponding positional argument |
| | 12 | 579 | | var arg = positionalArgs[inputParamIndex]; |
| | 12 | 580 | | var value = CompileExpression(arg.Value, param.ParameterType); |
| | 12 | 581 | | ctorArgs.Add(value); |
| | | 582 | | } |
| | 24 | 583 | | else if (param.IsOptional) |
| | | 584 | | { |
| | | 585 | | // This is an optional parameter (like CallerFilePath) - use its default value |
| | 24 | 586 | | ctorArgs.Add(param.DefaultValue); |
| | | 587 | | } |
| | | 588 | | else |
| | | 589 | | { |
| | | 590 | | // This shouldn't happen if our filtering is correct |
| | 0 | 591 | | throw new InvalidOperationException( |
| | 0 | 592 | | $"Unexpected non-optional, non-Input<T> parameter '{param.Name}' in constructor for '{activityType.N |
| | | 593 | | } |
| | | 594 | | } |
| | | 595 | | |
| | | 596 | | // Instantiate the activity using the constructor |
| | 12 | 597 | | var activity = (IActivity)selectedCtor.Invoke(ctorArgs.ToArray()); |
| | 12 | 598 | | return activity; |
| | | 599 | | } |
| | | 600 | | |
| | | 601 | | private static string MapLanguageName(string dslLanguage) => |
| | 12 | 602 | | LanguageMappings.TryGetValue(dslLanguage, out var mapped) ? mapped : dslLanguage; |
| | | 603 | | } |