(t *testing.T)
| 1818 | } |
| 1819 | |
| 1820 | func TestCustomInterpreterDecoratorV2(t *testing.T) { |
| 1821 | var lastInstruction interpreter.InterpretableV2 |
| 1822 | optimizeArith := func(i interpreter.InterpretableV2) (interpreter.InterpretableV2, error) { |
| 1823 | lastInstruction = i |
| 1824 | // Only optimize the instruction if it is a call. |
| 1825 | call, ok := i.(interpreter.InterpretableCall) |
| 1826 | if !ok { |
| 1827 | return i, nil |
| 1828 | } |
| 1829 | // Only optimize the math functions when they have constant arguments. |
| 1830 | switch call.Function() { |
| 1831 | case operators.Add, |
| 1832 | operators.Subtract, |
| 1833 | operators.Multiply, |
| 1834 | operators.Divide: |
| 1835 | // These are all binary operators so they should have two arguments |
| 1836 | args := call.Args() |
| 1837 | _, lhsIsConst := args[0].(interpreter.InterpretableConst) |
| 1838 | _, rhsIsConst := args[1].(interpreter.InterpretableConst) |
| 1839 | // When the values are constant then the call can be evaluated with |
| 1840 | // an empty activation and the value returns as a constant. |
| 1841 | if !lhsIsConst || !rhsIsConst { |
| 1842 | return i, nil |
| 1843 | } |
| 1844 | val := call.Eval(interpreter.EmptyActivation()) |
| 1845 | if types.IsError(val) { |
| 1846 | return nil, val.(*types.Err) |
| 1847 | } |
| 1848 | return interpreter.NewConstValue(call.ID(), val), nil |
| 1849 | default: |
| 1850 | return i, nil |
| 1851 | } |
| 1852 | } |
| 1853 | |
| 1854 | env := testEnv(t, Variable("foo", IntType)) |
| 1855 | ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`) |
| 1856 | if iss.Err() != nil { |
| 1857 | t.Fatalf("env.Compile() failed: %v", iss.Err()) |
| 1858 | } |
| 1859 | _, err := env.Program(ast, |
| 1860 | EvalOptions(OptPartialEval), |
| 1861 | CustomDecoratorV2(optimizeArith)) |
| 1862 | if err != nil { |
| 1863 | t.Fatalf("env.Program() failed: %v", err) |
| 1864 | } |
| 1865 | call, ok := lastInstruction.(interpreter.InterpretableCall) |
| 1866 | if !ok { |
| 1867 | t.Errorf("got %v, expected call", lastInstruction) |
| 1868 | } |
| 1869 | args := call.Args() |
| 1870 | lhs := args[0] |
| 1871 | lastAttr, ok := lhs.(interpreter.InterpretableAttribute) |
| 1872 | if !ok { |
| 1873 | t.Errorf("got %v, wanted attribute", lhs) |
| 1874 | } |
| 1875 | absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute) |
| 1876 | varNames := absAttr.CandidateVariableNames() |
| 1877 | if len(varNames) != 1 || varNames[0] != "foo" { |
nothing calls this directly
no test coverage detected