forked from mendixlabs/mxcli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_microflows_builder_control.go
More file actions
459 lines (403 loc) · 16.2 KB
/
cmd_microflows_builder_control.go
File metadata and controls
459 lines (403 loc) · 16.2 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
// SPDX-License-Identifier: Apache-2.0
// Package executor - Microflow flow graph: IF/ELSE and LOOP control flow builders
package executor
import (
"strings"
"github.com/mendixlabs/mxcli/mdl/ast"
"github.com/mendixlabs/mxcli/mdl/types"
"github.com/mendixlabs/mxcli/model"
"github.com/mendixlabs/mxcli/sdk/microflows"
)
// addIfStatement creates an IF/THEN/ELSE statement using ExclusiveSplit and ExclusiveMerge.
// Layout strategy:
// - IF with ELSE: TRUE path goes horizontal (happy path), FALSE path goes below
// - IF without ELSE: TRUE path goes below, FALSE path goes horizontal (happy path)
// When a branch ends with RETURN, it terminates at its own EndEvent and does not
// connect to the merge. When both branches end with RETURN, no merge is created.
func (fb *flowBuilder) addIfStatement(s *ast.IfStmt) model.ID {
// First, measure the branches to know how much space they need
thenBounds := fb.measurer.measureStatements(s.ThenBody)
elseBounds := fb.measurer.measureStatements(s.ElseBody)
// Calculate branch width (max of both branches)
branchWidth := max(thenBounds.Width, elseBounds.Width)
if branchWidth == 0 {
branchWidth = HorizontalSpacing / 2
}
// Check if branches end with RETURN (creating their own EndEvents)
thenReturns := lastStmtIsReturn(s.ThenBody)
hasElseBody := len(s.ElseBody) > 0
elseReturns := hasElseBody && lastStmtIsReturn(s.ElseBody)
bothReturn := hasElseBody && thenReturns && elseReturns
// Save/restore endsWithReturn around branch processing to avoid
// a branch's RETURN affecting the parent flow state prematurely
savedEndsWithReturn := fb.endsWithReturn
// Save current center line position
splitX := fb.posX
centerY := fb.posY // This is the center line for the happy path
// Decide whether the IF condition is a rule call or a plain expression.
// A rule-based split must be serialized as Microflows$RuleSplitCondition;
// emitting ExpressionSplitCondition for a rule call causes Studio Pro to
// raise CE0117 "Error(s) in expression".
caption := fb.exprToString(s.Condition)
splitCondition := fb.buildSplitCondition(s.Condition, caption)
split := µflows.ExclusiveSplit{
BaseMicroflowObject: microflows.BaseMicroflowObject{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Position: model.Point{X: splitX, Y: centerY},
Size: model.Size{Width: SplitWidth, Height: SplitHeight},
},
Caption: caption,
SplitCondition: splitCondition,
ErrorHandlingType: microflows.ErrorHandlingTypeRollback,
}
fb.objects = append(fb.objects, split)
splitID := split.ID
// Apply this IF's own annotations (e.g. @caption, @annotation) to the split
// BEFORE recursing into branch bodies. Otherwise a nested statement's annotations
// would overwrite fb.pendingAnnotations (shared state) and the outer loop in
// buildFlowGraph would then attach the wrong caption/annotation to this split.
if fb.pendingAnnotations != nil {
fb.applyAnnotations(splitID, fb.pendingAnnotations)
fb.pendingAnnotations = nil
}
// Calculate merge position (after the longest branch)
mergeX := splitX + SplitWidth + HorizontalSpacing/2 + branchWidth + HorizontalSpacing/2
// Determine if the merge would have 2+ incoming edges (non-redundant).
// Skip merge when only one branch flows into it (the other returns).
needMerge := false
if !bothReturn {
if hasElseBody {
needMerge = !thenReturns && !elseReturns // both branches continue → 2 inputs
} else {
needMerge = !thenReturns // THEN continues + FALSE path → 2 inputs
}
}
var mergeID model.ID
if needMerge {
merge := µflows.ExclusiveMerge{
BaseMicroflowObject: microflows.BaseMicroflowObject{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Position: model.Point{X: mergeX, Y: centerY},
Size: model.Size{Width: MergeSize, Height: MergeSize},
},
}
fb.objects = append(fb.objects, merge)
mergeID = merge.ID
}
thenStartX := splitX + SplitWidth + HorizontalSpacing/2
if hasElseBody {
// IF WITH ELSE: TRUE path horizontal (happy path), FALSE path below
fb.posX = thenStartX
fb.posY = centerY
fb.endsWithReturn = false
var lastThenID model.ID
for _, stmt := range s.ThenBody {
actID := fb.addStatement(stmt)
if actID != "" {
if lastThenID == "" {
// First statement in THEN - connect from split with "true" case
fb.flows = append(fb.flows, newHorizontalFlowWithCase(splitID, actID, "true"))
} else {
fb.flows = append(fb.flows, newHorizontalFlow(lastThenID, actID))
}
// For nested compound statements, use their exit point
if fb.nextConnectionPoint != "" {
lastThenID = fb.nextConnectionPoint
fb.nextConnectionPoint = ""
} else {
lastThenID = actID
}
}
}
// Connect THEN body to merge only if it doesn't end with RETURN and a merge exists.
// When needMerge=false, the continuing branch is wired up by the parent via
// nextConnectionPoint/nextFlowCase, so we must not emit a dangling flow here.
if !thenReturns && needMerge {
if lastThenID != "" {
fb.flows = append(fb.flows, newHorizontalFlow(lastThenID, mergeID))
} else {
// Empty THEN body - connect split directly to merge with true case
fb.flows = append(fb.flows, newHorizontalFlowWithCase(splitID, mergeID, "true"))
}
}
// Process ELSE body (below the THEN path)
elseCenterY := centerY + VerticalSpacing
fb.posX = thenStartX
fb.posY = elseCenterY
fb.endsWithReturn = false
var lastElseID model.ID
for _, stmt := range s.ElseBody {
actID := fb.addStatement(stmt)
if actID != "" {
if lastElseID == "" {
// First statement in ELSE - connect from split going down (false path)
fb.flows = append(fb.flows, newDownwardFlowWithCase(splitID, actID, "false"))
} else {
fb.flows = append(fb.flows, newHorizontalFlow(lastElseID, actID))
}
// For nested compound statements, use their exit point
if fb.nextConnectionPoint != "" {
lastElseID = fb.nextConnectionPoint
fb.nextConnectionPoint = ""
} else {
lastElseID = actID
}
}
}
// Connect ELSE body to merge only if it doesn't end with RETURN and a merge exists.
// When needMerge=false, the continuing branch is handled by the parent; emitting
// a flow with an empty mergeID would create an orphan SequenceFlow.
if !elseReturns && needMerge {
if lastElseID != "" {
fb.flows = append(fb.flows, newUpwardFlow(lastElseID, mergeID))
}
}
} else {
// IF WITHOUT ELSE: FALSE path horizontal (happy path), TRUE path below
// This keeps the "do nothing" path straight and the "do something" path below
if needMerge {
// FALSE path: connect split directly to merge horizontally
fb.flows = append(fb.flows, newHorizontalFlowWithCase(splitID, mergeID, "false"))
}
// When !needMerge (thenReturns): FALSE flow is deferred — the parent will
// connect splitID to the next activity with nextFlowCase="false".
// TRUE path: goes below the main line
thenCenterY := centerY + VerticalSpacing
fb.posX = thenStartX
fb.posY = thenCenterY
fb.endsWithReturn = false
var lastThenID model.ID
for _, stmt := range s.ThenBody {
actID := fb.addStatement(stmt)
if actID != "" {
if lastThenID == "" {
// First statement in THEN - connect from split going down with "true" case
fb.flows = append(fb.flows, newDownwardFlowWithCase(splitID, actID, "true"))
} else {
fb.flows = append(fb.flows, newHorizontalFlow(lastThenID, actID))
}
// For nested compound statements, use their exit point
if fb.nextConnectionPoint != "" {
lastThenID = fb.nextConnectionPoint
fb.nextConnectionPoint = ""
} else {
lastThenID = actID
}
}
}
// Connect THEN body to merge only if it doesn't end with RETURN and a merge exists.
// With no ELSE + thenReturns, needMerge=false and the FALSE path is threaded through
// the parent — any flow emitted here would dangle with mergeID="".
if !thenReturns && needMerge {
if lastThenID != "" {
fb.flows = append(fb.flows, newUpwardFlow(lastThenID, mergeID))
} else {
// Empty THEN body - connect split directly to merge going down and back up
fb.flows = append(fb.flows, newDownwardFlowWithCase(splitID, mergeID, "true"))
}
}
}
// If both branches end with RETURN, the flow terminates here
if bothReturn {
fb.endsWithReturn = true
return splitID
}
// Restore endsWithReturn - a single branch returning doesn't end the overall flow
fb.endsWithReturn = savedEndsWithReturn
if needMerge {
// Update position to after the merge, on the happy path center line
fb.posX = mergeX + MergeSize + HorizontalSpacing/2
fb.posY = centerY
fb.nextConnectionPoint = mergeID
} else {
// No merge: the split's continuing branch connects directly to the next activity.
// Position after the split, past the downward branch's horizontal extent.
afterSplit := splitX + SplitWidth + HorizontalSpacing
afterBranch := thenStartX + thenBounds.Width + HorizontalSpacing/2
if !hasElseBody {
fb.posX = max(afterSplit, afterBranch)
} else {
fb.posX = max(afterSplit, afterBranch)
}
fb.posY = centerY
fb.nextConnectionPoint = splitID
// Tell parent to attach the case value on the next flow
if hasElseBody {
if thenReturns {
fb.nextFlowCase = "false"
} else {
fb.nextFlowCase = "true"
}
} else {
fb.nextFlowCase = "false" // IF without ELSE: false is the continuing path
}
}
return splitID
}
// addLoopStatement creates a LOOP statement using LoopedActivity.
// Layout: Auto-sizes the loop box to fit content with padding
func (fb *flowBuilder) addLoopStatement(s *ast.LoopStmt) model.ID {
// Snapshot & clear this loop's own annotations so the body's recursive
// addStatement calls can't consume them. We re-apply to the loop activity
// after it's created below.
savedLoopAnnotations := fb.pendingAnnotations
fb.pendingAnnotations = nil
// First, measure the loop body to determine size
bodyBounds := fb.measurer.measureStatements(s.Body)
// Calculate loop box size with padding
// Extra width for iterator icon and its label (100 pixels)
iteratorSpace := 100
loopWidth := max(bodyBounds.Width+2*LoopPadding+iteratorSpace, MinLoopWidth)
loopHeight := max(bodyBounds.Height+2*LoopPadding, MinLoopHeight)
// Inner positioning: activities need to be offset from the iterator icon
// The iterator takes up space in the top-left, so we need extra X offset
// Looking at working Mendix loops, inner content starts further right
innerStartX := LoopPadding + iteratorSpace // Extra offset for iterator icon and label
innerStartY := LoopPadding + ActivityHeight/2 // Center activities vertically with some padding
loopLeftX := fb.posX
loopCenterX := loopLeftX + loopWidth/2
if s.Annotations != nil && s.Annotations.Position != nil {
loopCenterX = s.Annotations.Position.X
loopLeftX = loopCenterX - loopWidth/2
}
// Add loop variable to varTypes with element type derived from list type
// If $ProductList is "List of MfTest.Product", then $Product is "MfTest.Product"
if fb.varTypes != nil {
listType := fb.varTypes[s.ListVariable]
if after, ok := strings.CutPrefix(listType, "List of "); ok {
elementType := after
fb.varTypes[s.LoopVariable] = elementType
}
}
// Build nested ObjectCollection for loop body
loopBuilder := &flowBuilder{
posX: innerStartX,
posY: innerStartY,
baseY: innerStartY,
spacing: HorizontalSpacing,
varTypes: fb.varTypes, // Share variable scope
declaredVars: fb.declaredVars, // Share declared vars (fixes nil map panic)
measurer: fb.measurer, // Share measurer
backend: fb.backend, // Share backend
hierarchy: fb.hierarchy, // Share hierarchy
restServices: fb.restServices, // Share REST services for parameter classification
}
// Process loop body statements and connect them with flows
var lastBodyID model.ID
for _, stmt := range s.Body {
actID := loopBuilder.addStatement(stmt)
if actID != "" {
if lastBodyID != "" {
loopBuilder.flows = append(loopBuilder.flows, newHorizontalFlow(lastBodyID, actID))
}
// Handle nextConnectionPoint for compound statements (nested IF, etc.)
if loopBuilder.nextConnectionPoint != "" {
lastBodyID = loopBuilder.nextConnectionPoint
loopBuilder.nextConnectionPoint = ""
} else {
lastBodyID = actID
}
}
}
// Create LoopedActivity with calculated size
// Position is the CENTER point (RelativeMiddlePoint in Mendix)
loop := µflows.LoopedActivity{
BaseMicroflowObject: microflows.BaseMicroflowObject{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Position: model.Point{X: loopCenterX, Y: fb.posY},
Size: model.Size{Width: loopWidth, Height: loopHeight},
},
LoopSource: µflows.IterableList{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
ListVariableName: s.ListVariable,
VariableName: s.LoopVariable,
},
ObjectCollection: µflows.MicroflowObjectCollection{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Objects: loopBuilder.objects,
Flows: nil, // Internal flows go at top-level, not inside the loop's ObjectCollection
},
ErrorHandlingType: microflows.ErrorHandlingTypeRollback,
}
fb.objects = append(fb.objects, loop)
// Add the internal flows to the parent's flows (top-level), not inside loop
// This is how Mendix stores them - all flows at the microflow level
fb.flows = append(fb.flows, loopBuilder.flows...)
// Re-apply this loop's own annotations now that its activity exists.
if savedLoopAnnotations != nil {
fb.applyAnnotations(loop.ID, savedLoopAnnotations)
}
fb.posX = loopLeftX + loopWidth + HorizontalSpacing
return loop.ID
}
// addWhileStatement creates a WHILE loop using LoopedActivity with WhileLoopCondition.
// Layout matches addLoopStatement but without iterator icon space.
func (fb *flowBuilder) addWhileStatement(s *ast.WhileStmt) model.ID {
// Snapshot & clear this WHILE's own annotations so the body's recursive
// addStatement calls can't consume them (see addLoopStatement).
savedWhileAnnotations := fb.pendingAnnotations
fb.pendingAnnotations = nil
bodyBounds := fb.measurer.measureStatements(s.Body)
loopWidth := max(bodyBounds.Width+2*LoopPadding, MinLoopWidth)
loopHeight := max(bodyBounds.Height+2*LoopPadding, MinLoopHeight)
innerStartX := LoopPadding
innerStartY := LoopPadding + ActivityHeight/2
loopLeftX := fb.posX
loopCenterX := loopLeftX + loopWidth/2
if s.Annotations != nil && s.Annotations.Position != nil {
loopCenterX = s.Annotations.Position.X
loopLeftX = loopCenterX - loopWidth/2
}
loopBuilder := &flowBuilder{
posX: innerStartX,
posY: innerStartY,
baseY: innerStartY,
spacing: HorizontalSpacing,
varTypes: fb.varTypes,
declaredVars: fb.declaredVars,
measurer: fb.measurer,
backend: fb.backend,
hierarchy: fb.hierarchy,
restServices: fb.restServices,
}
var lastBodyID model.ID
for _, stmt := range s.Body {
actID := loopBuilder.addStatement(stmt)
if actID != "" {
if lastBodyID != "" {
loopBuilder.flows = append(loopBuilder.flows, newHorizontalFlow(lastBodyID, actID))
}
if loopBuilder.nextConnectionPoint != "" {
lastBodyID = loopBuilder.nextConnectionPoint
loopBuilder.nextConnectionPoint = ""
} else {
lastBodyID = actID
}
}
}
whileExpr := fb.exprToString(s.Condition)
loop := µflows.LoopedActivity{
BaseMicroflowObject: microflows.BaseMicroflowObject{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Position: model.Point{X: loopCenterX, Y: fb.posY},
Size: model.Size{Width: loopWidth, Height: loopHeight},
},
LoopSource: µflows.WhileLoopCondition{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
WhileExpression: whileExpr,
},
ObjectCollection: µflows.MicroflowObjectCollection{
BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())},
Objects: loopBuilder.objects,
Flows: nil,
},
ErrorHandlingType: microflows.ErrorHandlingTypeRollback,
}
fb.objects = append(fb.objects, loop)
fb.flows = append(fb.flows, loopBuilder.flows...)
if savedWhileAnnotations != nil {
fb.applyAnnotations(loop.ID, savedWhileAnnotations)
}
fb.posX = loopLeftX + loopWidth + HorizontalSpacing
return loop.ID
}