MCPcopy Create free account
hub / github.com/github/gh-aw / optimizeAndNode

Function optimizeAndNode

pkg/workflow/expression_optimizer.go:209–315  ·  view source on GitHub ↗

--- node-specific optimisers ------------------------------------------------

(n *AndNode)

Source from the content-addressed store, hash-verified

207// --- node-specific optimisers ------------------------------------------------
208
209func optimizeAndNode(n *AndNode) ConditionNode {
210 // Bottom-up: optimise children first.
211 left := optimizeNode(n.Left)
212 right := optimizeNode(n.Right)
213
214 // Annihilation: A && false → false (before flattening for early exit).
215 if isBoolLiteral(left, false) || isBoolLiteral(right, false) {
216 expressionOptimizerLog.Printf("AND annihilation: %s && %s → false", left.Render(), right.Render())
217 return &BooleanLiteralNode{Value: false}
218 }
219
220 // Flatten the entire AND chain so that rules can operate across nesting levels.
221 // e.g. A && (A && B) → [A, A, B] → dedup → [A, B] → A && B
222 terms := collectAndTerms(&AndNode{Left: left, Right: right})
223
224 // Annihilation within the flat list (covers cases after child optimisation).
225 for _, t := range terms {
226 if isBoolLiteral(t, false) {
227 expressionOptimizerLog.Printf("AND annihilation (flatten): false term → false")
228 return &BooleanLiteralNode{Value: false}
229 }
230 }
231
232 // Identity: filter out `true` literals, but keep them when any term is a
233 // status function (to preserve status-function semantics).
234 hasStatusFuncInTerms := slices.ContainsFunc(terms, containsStatusFunc)
235 filtered := make([]ConditionNode, 0, len(terms))
236 for _, t := range terms {
237 if isBoolLiteral(t, true) && !hasStatusFuncInTerms {
238 expressionOptimizerLog.Printf("AND identity (flatten): removed true literal")
239 continue
240 }
241 filtered = append(filtered, t)
242 }
243 if len(filtered) == 0 {
244 return &BooleanLiteralNode{Value: true}
245 }
246
247 // Deduplicate terms by rendered form (safe even for status functions).
248 seen := make(map[string]struct{}, len(filtered))
249 deduped := make([]ConditionNode, 0, len(filtered))
250 for _, t := range filtered {
251 key := t.Render()
252 if _, exists := seen[key]; !exists {
253 seen[key] = struct{}{}
254 deduped = append(deduped, t)
255 } else {
256 expressionOptimizerLog.Printf("AND dedup: removing duplicate term %q", key)
257 }
258 }
259 if len(deduped) == 1 {
260 return deduped[0]
261 }
262
263 // Complement: A && !A → false (skip when status functions present).
264 if !hasStatusFuncInTerms {
265 for i := range deduped {
266 for j := i + 1; j < len(deduped); j++ {

Callers 1

optimizeNodeFunction · 0.85

Calls 9

optimizeNodeFunction · 0.85
isBoolLiteralFunction · 0.85
collectAndTermsFunction · 0.85
isNegationOfFunction · 0.85
collectOrTermsFunction · 0.85
nodesEqualFunction · 0.85
rebuildAndChainFunction · 0.85
RenderMethod · 0.65
PrintfMethod · 0.45

Tested by

no test coverage detected