Optimize applies a sequence of optimizations to an Ast within a given environment. If issues are encountered, the Issues.Err() return value will be non-nil.
(env *Env, a *Ast)
| 75 | // |
| 76 | // If issues are encountered, the Issues.Err() return value will be non-nil. |
| 77 | func (opt *StaticOptimizer) Optimize(env *Env, a *Ast) (*Ast, *Issues) { |
| 78 | // Make a copy of the AST to be optimized. |
| 79 | optimized := ast.Copy(a.NativeRep()) |
| 80 | source := a.Source() |
| 81 | sourceInfo := optimized.SourceInfo() |
| 82 | if opt.sourceOverride != nil { |
| 83 | source = *opt.sourceOverride |
| 84 | sourceInfo = ast.NewSourceInfo(*opt.sourceOverride) |
| 85 | } |
| 86 | ids := newIDGenerator(ast.MaxID(a.NativeRep())) |
| 87 | |
| 88 | // Create the optimizer context, could be pooled in the future. |
| 89 | issues := NewIssues(common.NewErrors(source)) |
| 90 | baseFac := ast.NewExprFactory() |
| 91 | exprFac := &optimizerExprFactory{ |
| 92 | idGenerator: ids, |
| 93 | fac: baseFac, |
| 94 | sourceInfo: sourceInfo, |
| 95 | } |
| 96 | ctx := &OptimizerContext{ |
| 97 | optimizerExprFactory: exprFac, |
| 98 | Env: env, |
| 99 | Issues: issues, |
| 100 | } |
| 101 | |
| 102 | // Apply the optimizations sequentially. |
| 103 | for _, o := range opt.optimizers { |
| 104 | optimized = o.Optimize(ctx, optimized) |
| 105 | if issues.Err() != nil { |
| 106 | return nil, issues |
| 107 | } |
| 108 | // Normalize expression id metadata including coordination with macro call metadata. |
| 109 | freshIDGen := newIDGenerator(0) |
| 110 | info := optimized.SourceInfo() |
| 111 | expr := optimized.Expr() |
| 112 | normalizeIDs(freshIDGen.renumberStable, expr, info) |
| 113 | cleanupMacroRefs(expr, info) |
| 114 | |
| 115 | // Recheck the updated expression for any possible type-agreement or validation errors. |
| 116 | parsed := &Ast{ |
| 117 | source: source, |
| 118 | impl: ast.NewAST(expr, info)} |
| 119 | checked, iss := ctx.Check(parsed) |
| 120 | if iss.Err() != nil { |
| 121 | return nil, iss |
| 122 | } |
| 123 | optimized = checked.NativeRep() |
| 124 | } |
| 125 | |
| 126 | // Return the optimized result. |
| 127 | return &Ast{ |
| 128 | source: source, |
| 129 | impl: optimized, |
| 130 | }, nil |
| 131 | } |
| 132 | |
| 133 | // normalizeIDs ensures that the metadata present with an AST is reset in a manner such |
| 134 | // that the ids within the expression correspond to the ids within macros. |