lang: Add function values and lambdas
This adds a giant missing piece of the language: proper function values! It is lovely to now understand why early programming language designers didn't implement these, but a joy to now reap the benefits of them. In adding these, many other changes had to be made to get them to "fit" correctly. This improved the code and fixed a number of bugs. Unfortunately this touched many areas of the code, and since I was learning how to do all of this for the first time, I've squashed most of my work into a single commit. Some more information: * This adds over 70 new tests to verify the new functionality. * Functions, global variables, and classes can all be implemented natively in mcl and built into core packages. * A new compiler step called "Ordering" was added. It is called by the SetScope step, and determines statement ordering and shadowing precedence formally. It helped remove at least one bug and provided the additional analysis required to properly capture variables when implementing function generators and closures. * The type unification code was improved to handle the new cases. * Light copying of Node's allowed our function graphs to be more optimal and share common vertices and edges. For example, if two different closures capture a variable $x, they'll both use the same copy when running the function, since the compiler can prove if they're identical. * Some areas still need improvements, but this is ready for mainstream testing and use!
This commit is contained in:
@@ -28,6 +28,23 @@ import (
|
||||
const (
|
||||
// Name is the prefix for our solver log messages.
|
||||
Name = "solver: simple"
|
||||
|
||||
// ErrAmbiguous means we couldn't find a solution, but we weren't
|
||||
// inconsistent.
|
||||
ErrAmbiguous = interfaces.Error("can't unify, no equalities were consumed, we're ambiguous")
|
||||
|
||||
// AllowRecursion specifies whether we're allowed to use the recursive
|
||||
// solver or not. It uses an absurd amount of memory, and might hang
|
||||
// your system if a simple solution doesn't exist.
|
||||
AllowRecursion = false
|
||||
|
||||
// RecursionDepthLimit specifies the max depth that is allowed.
|
||||
// FIXME: RecursionDepthLimit is not currently implemented
|
||||
RecursionDepthLimit = 5 // TODO: pick a better value ?
|
||||
|
||||
// RecursionInvariantLimit specifies the max number of invariants we can
|
||||
// recurse into.
|
||||
RecursionInvariantLimit = 5 // TODO: pick a better value ?
|
||||
)
|
||||
|
||||
// SimpleInvariantSolverLogger is a wrapper which returns a
|
||||
@@ -44,74 +61,90 @@ func SimpleInvariantSolverLogger(logf func(format string, v ...interface{})) fun
|
||||
// It is intended to be very simple, even if it's computationally inefficient.
|
||||
func SimpleInvariantSolver(invariants []interfaces.Invariant, expected []interfaces.Expr, logf func(format string, v ...interface{})) (*InvariantSolution, error) {
|
||||
debug := false // XXX: add to interface
|
||||
process := func(invariants []interfaces.Invariant) ([]interfaces.Invariant, []*ExclusiveInvariant, error) {
|
||||
equalities := []interfaces.Invariant{}
|
||||
exclusives := []*ExclusiveInvariant{}
|
||||
|
||||
for _, x := range invariants {
|
||||
switch invariant := x.(type) {
|
||||
case *EqualsInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityInvariantList:
|
||||
// de-construct this list variant into a series
|
||||
// of equality variants so that our solver can
|
||||
// be implemented more simply...
|
||||
if len(invariant.Exprs) < 2 {
|
||||
return nil, nil, fmt.Errorf("list invariant needs at least two elements")
|
||||
}
|
||||
for i := 0; i < len(invariant.Exprs)-1; i++ {
|
||||
invar := &EqualityInvariant{
|
||||
Expr1: invariant.Exprs[i],
|
||||
Expr2: invariant.Exprs[i+1],
|
||||
}
|
||||
equalities = append(equalities, invar)
|
||||
}
|
||||
|
||||
case *EqualityWrapListInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapMapInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapStructInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapFuncInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapCallInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
// contains a list of invariants which this represents
|
||||
case *ConjunctionInvariant:
|
||||
for _, invar := range invariant.Invariants {
|
||||
equalities = append(equalities, invar)
|
||||
}
|
||||
|
||||
case *ExclusiveInvariant:
|
||||
// these are special, note the different list
|
||||
if len(invariant.Invariants) > 0 {
|
||||
exclusives = append(exclusives, invariant)
|
||||
}
|
||||
|
||||
case *AnyInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unknown invariant type: %T", x)
|
||||
}
|
||||
}
|
||||
|
||||
return equalities, exclusives, nil
|
||||
}
|
||||
|
||||
logf("%s: invariants:", Name)
|
||||
for i, x := range invariants {
|
||||
logf("invariant(%d): %T: %s", i, x, x)
|
||||
}
|
||||
|
||||
solved := make(map[interfaces.Expr]*types.Type)
|
||||
equalities := []interfaces.Invariant{}
|
||||
exclusives := []*ExclusiveInvariant{}
|
||||
// iterate through all invariants, flattening and sorting the list...
|
||||
for _, x := range invariants {
|
||||
switch invariant := x.(type) {
|
||||
case *EqualsInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityInvariantList:
|
||||
// de-construct this list variant into a series
|
||||
// of equality variants so that our solver can
|
||||
// be implemented more simply...
|
||||
if len(invariant.Exprs) < 2 {
|
||||
return nil, fmt.Errorf("list invariant needs at least two elements")
|
||||
}
|
||||
for i := 0; i < len(invariant.Exprs)-1; i++ {
|
||||
invar := &EqualityInvariant{
|
||||
Expr1: invariant.Exprs[i],
|
||||
Expr2: invariant.Exprs[i+1],
|
||||
}
|
||||
equalities = append(equalities, invar)
|
||||
}
|
||||
|
||||
case *EqualityWrapListInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapMapInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapStructInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
case *EqualityWrapFuncInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
// contains a list of invariants which this represents
|
||||
case *ConjunctionInvariant:
|
||||
for _, invar := range invariant.Invariants {
|
||||
equalities = append(equalities, invar)
|
||||
}
|
||||
|
||||
case *ExclusiveInvariant:
|
||||
// these are special, note the different list
|
||||
if len(invariant.Invariants) > 0 {
|
||||
exclusives = append(exclusives, invariant)
|
||||
}
|
||||
|
||||
case *AnyInvariant:
|
||||
equalities = append(equalities, invariant)
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown invariant type: %T", x)
|
||||
}
|
||||
equalities, exclusives, err := process(invariants)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// XXX: if these partials all shared the same variable definition, would
|
||||
// it all work??? Maybe we don't even need the first map prefix...
|
||||
listPartials := make(map[interfaces.Expr]map[interfaces.Expr]*types.Type)
|
||||
mapPartials := make(map[interfaces.Expr]map[interfaces.Expr]*types.Type)
|
||||
structPartials := make(map[interfaces.Expr]map[interfaces.Expr]*types.Type)
|
||||
funcPartials := make(map[interfaces.Expr]map[interfaces.Expr]*types.Type)
|
||||
callPartials := make(map[interfaces.Expr]map[interfaces.Expr]*types.Type)
|
||||
|
||||
isSolved := func(solved map[interfaces.Expr]*types.Type) bool {
|
||||
for _, x := range expected {
|
||||
@@ -461,6 +494,42 @@ Loop:
|
||||
continue
|
||||
}
|
||||
|
||||
case *EqualityWrapCallInvariant:
|
||||
// the logic is slightly different here, because
|
||||
// we can only go from the func type to the call
|
||||
// type as we can't do the reverse determination
|
||||
if _, exists := callPartials[eq.Expr2Func]; !exists {
|
||||
callPartials[eq.Expr2Func] = make(map[interfaces.Expr]*types.Type)
|
||||
}
|
||||
|
||||
if typ, exists := solved[eq.Expr2Func]; exists {
|
||||
// wow, now known, so tell the partials!
|
||||
if typ.Kind != types.KindFunc {
|
||||
return nil, fmt.Errorf("expected: %s, got: %s", types.KindFunc, typ.Kind)
|
||||
}
|
||||
callPartials[eq.Expr2Func][eq.Expr1] = typ.Out
|
||||
}
|
||||
|
||||
typ, ready := callPartials[eq.Expr2Func][eq.Expr1]
|
||||
if ready { // ready to solve
|
||||
if t, exists := solved[eq.Expr1]; exists {
|
||||
if err := t.Cmp(typ); err != nil {
|
||||
return nil, errwrap.Wrapf(err, "can't unify, invariant illogicality with call")
|
||||
}
|
||||
}
|
||||
// sub checks
|
||||
if t, exists := solved[eq.Expr2Func]; exists {
|
||||
if err := t.Out.Cmp(typ); err != nil {
|
||||
return nil, errwrap.Wrapf(err, "can't unify, invariant illogicality with call out")
|
||||
}
|
||||
}
|
||||
|
||||
solved[eq.Expr1] = typ // yay, we learned something!
|
||||
used = append(used, i) // mark equality as used up
|
||||
logf("%s: solved call wrap partial", Name)
|
||||
continue
|
||||
}
|
||||
|
||||
// regular matching
|
||||
case *EqualityInvariant:
|
||||
typ1, exists1 := solved[eq.Expr1]
|
||||
@@ -533,16 +602,21 @@ Loop:
|
||||
logf("%s: solved early with %d exclusives left!", Name, len(exclusives))
|
||||
} else {
|
||||
logf("%s: unsolved with %d exclusives left!", Name, len(exclusives))
|
||||
if debug {
|
||||
for i, x := range exclusives {
|
||||
logf("%s: exclusive(%d) left: %s", Name, i, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check for consistency against remaining invariants
|
||||
logf("%s: checking for consistency against %d exclusives...", Name, len(exclusives))
|
||||
done := []int{}
|
||||
for i, invar := range exclusives {
|
||||
// test each one to see if at least one works
|
||||
match, err := invar.Matches(solved)
|
||||
if err != nil {
|
||||
if debug {
|
||||
logf("exclusive invar failed: %+v", invar)
|
||||
}
|
||||
logf("exclusive invar failed: %+v", invar)
|
||||
return nil, errwrap.Wrapf(err, "inconsistent exclusive")
|
||||
}
|
||||
if !match {
|
||||
@@ -550,30 +624,19 @@ Loop:
|
||||
}
|
||||
done = append(done, i)
|
||||
}
|
||||
logf("%s: removed %d consistent exclusives...", Name, len(done))
|
||||
|
||||
// remove exclusives that matched correctly
|
||||
// Remove exclusives that matched correctly.
|
||||
for i := len(done) - 1; i >= 0; i-- {
|
||||
ix := done[i] // delete index that was marked as done!
|
||||
exclusives = append(exclusives[:ix], exclusives[ix+1:]...)
|
||||
}
|
||||
|
||||
if len(exclusives) == 0 {
|
||||
break Loop
|
||||
// If we removed any exclusives, then we can start over.
|
||||
if len(done) > 0 {
|
||||
continue Loop
|
||||
}
|
||||
|
||||
// TODO: Lastly, we could loop through each exclusive
|
||||
// and see if it only has a single, easy solution. For
|
||||
// example, if we know that an exclusive is A or B or C
|
||||
// and that B and C are inconsistent, then we can
|
||||
// replace the exclusive with a single invariant and
|
||||
// then run that through our solver. We can do this
|
||||
// iteratively (recursively in our case) so that if
|
||||
// we're lucky, we rarely need to run the raw exclusive
|
||||
// combinatorial solver which is slow.
|
||||
|
||||
// TODO: We could try and replace our combinatorial
|
||||
// exclusive solver with a real SAT solver algorithm.
|
||||
|
||||
// what have we learned for sure so far?
|
||||
partialSolutions := []interfaces.Invariant{}
|
||||
logf("%s: %d solved, %d unsolved, and %d exclusives left", Name, len(solved), len(equalities), len(exclusives))
|
||||
@@ -595,6 +658,69 @@ Loop:
|
||||
}
|
||||
}
|
||||
|
||||
// Lastly, we could loop through each exclusive and see
|
||||
// if it only has a single, easy solution. For example,
|
||||
// if we know that an exclusive is A or B or C, and that
|
||||
// B and C are inconsistent, then we can replace the
|
||||
// exclusive with a single invariant and then run that
|
||||
// through our solver. We can do this iteratively
|
||||
// (recursively for accuracy, but in our case via the
|
||||
// simplify method) so that if we're lucky, we rarely
|
||||
// need to run the raw exclusive combinatorial solver,
|
||||
// which is slow.
|
||||
logf("%s: attempting to simplify %d exclusives...", Name, len(exclusives))
|
||||
|
||||
done = []int{} // clear for re-use
|
||||
simplified := []interfaces.Invariant{}
|
||||
for i, invar := range exclusives {
|
||||
// The partialSolutions don't contain any other
|
||||
// exclusives... We look at each individually.
|
||||
s, err := invar.simplify(partialSolutions) // XXX: pass in the solver?
|
||||
if err != nil {
|
||||
logf("exclusive simplification failed: %+v", invar)
|
||||
continue
|
||||
}
|
||||
done = append(done, i)
|
||||
simplified = append(simplified, s...)
|
||||
}
|
||||
logf("%s: simplified %d exclusives...", Name, len(done))
|
||||
|
||||
// Remove exclusives that matched correctly.
|
||||
for i := len(done) - 1; i >= 0; i-- {
|
||||
ix := done[i] // delete index that was marked as done!
|
||||
exclusives = append(exclusives[:ix], exclusives[ix+1:]...)
|
||||
}
|
||||
|
||||
// Add new equalities and exclusives onto state globals.
|
||||
eq, ex, err := process(simplified) // process like at the top
|
||||
if err != nil {
|
||||
// programming error?
|
||||
return nil, errwrap.Wrapf(err, "processing error")
|
||||
}
|
||||
equalities = append(equalities, eq...)
|
||||
exclusives = append(exclusives, ex...)
|
||||
|
||||
// If we removed any exclusives, then we can start over.
|
||||
if len(done) > 0 {
|
||||
continue Loop
|
||||
}
|
||||
|
||||
// TODO: We could try and replace our combinatorial
|
||||
// exclusive solver with a real SAT solver algorithm.
|
||||
|
||||
if !AllowRecursion || len(exclusives) > RecursionInvariantLimit {
|
||||
logf("%s: %d solved, %d unsolved, and %d exclusives left", Name, len(solved), len(equalities), len(exclusives))
|
||||
for i, eq := range equalities {
|
||||
logf("%s: (%d) equality: %s", Name, i, eq)
|
||||
}
|
||||
for i, ex := range exclusives {
|
||||
logf("%s: (%d) exclusive: %s", Name, i, ex)
|
||||
}
|
||||
|
||||
// these can be very slow, so try to avoid them
|
||||
return nil, fmt.Errorf("only recursive solutions left")
|
||||
}
|
||||
|
||||
// let's try each combination, one at a time...
|
||||
for i, ex := range exclusivesProduct(exclusives) { // [][]interfaces.Invariant
|
||||
logf("%s: exclusive(%d):\n%+v", Name, i, ex)
|
||||
@@ -605,6 +731,7 @@ Loop:
|
||||
recursiveInvariants := []interfaces.Invariant{}
|
||||
recursiveInvariants = append(recursiveInvariants, partialSolutions...)
|
||||
recursiveInvariants = append(recursiveInvariants, ex...)
|
||||
// FIXME: implement RecursionDepthLimit
|
||||
logf("%s: recursing...", Name)
|
||||
solution, err := SimpleInvariantSolver(recursiveInvariants, expected, logf)
|
||||
if err != nil {
|
||||
@@ -617,7 +744,7 @@ Loop:
|
||||
}
|
||||
|
||||
// TODO: print ambiguity
|
||||
return nil, fmt.Errorf("can't unify, no equalities were consumed, we're ambiguous")
|
||||
return nil, ErrAmbiguous
|
||||
}
|
||||
// delete used equalities, in reverse order to preserve indexing!
|
||||
for i := len(used) - 1; i >= 0; i-- {
|
||||
|
||||
@@ -19,10 +19,12 @@ package unification
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/purpleidea/mgmt/lang/interfaces"
|
||||
"github.com/purpleidea/mgmt/lang/types"
|
||||
"github.com/purpleidea/mgmt/util/errwrap"
|
||||
)
|
||||
|
||||
// Unifier holds all the data that the Unify function will need for it to run.
|
||||
@@ -107,8 +109,22 @@ func (obj *Unifier) Unify() error {
|
||||
delete(exprMap, x.Expr) // remove everything we know about
|
||||
}
|
||||
if c := len(exprMap); c > 0 { // if there's anything left, it's bad...
|
||||
ptrs := []string{}
|
||||
disp := make(map[string]string) // display hack
|
||||
for i := range exprMap {
|
||||
s := fmt.Sprintf("%p", i) // pointer
|
||||
ptrs = append(ptrs, s)
|
||||
disp[s] = i.String()
|
||||
}
|
||||
sort.Strings(ptrs)
|
||||
// programming error!
|
||||
return fmt.Errorf("got %d unbound expr's", c)
|
||||
s := strings.Join(ptrs, ", ")
|
||||
|
||||
obj.Logf("got %d unbound expr's: %s", c, s)
|
||||
for i, s := range ptrs {
|
||||
obj.Logf("(%d) %s => %s", i, s, disp[s])
|
||||
}
|
||||
return fmt.Errorf("got %d unbound expr's: %s", c, s)
|
||||
}
|
||||
|
||||
if obj.Debug {
|
||||
@@ -160,6 +176,43 @@ func (obj *EqualsInvariant) Matches(solved map[interfaces.Expr]*types.Type) (boo
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
func (obj *EqualsInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// TODO: we could pass in a solver here
|
||||
//set := []interfaces.Invariant{}
|
||||
//set = append(set, obj)
|
||||
//set = append(set, partials...)
|
||||
//_, err := SimpleInvariantSolver(set, ...)
|
||||
//if err != nil {
|
||||
// // being ambiguous doesn't guarantee that we're possible
|
||||
// if err == ErrAmbiguous {
|
||||
// return nil // might be possible, might not be...
|
||||
// }
|
||||
// return err
|
||||
//}
|
||||
|
||||
// FIXME: This is not right because we want to know if the whole thing
|
||||
// works together, and as a result, the above solver is better, however,
|
||||
// the goal is to eliminate easy impossible solutions, so allow this!
|
||||
// XXX: Double check this is logical.
|
||||
solved := map[interfaces.Expr]*types.Type{
|
||||
obj.Expr: obj.Type,
|
||||
}
|
||||
for _, invar := range partials { // check each one
|
||||
_, err := invar.Matches(solved)
|
||||
if err != nil { // inconsistent, so it's not possible
|
||||
return errwrap.Wrapf(err, "not possible")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EqualityInvariant is an invariant that symbolizes that the two expressions
|
||||
// must have equivalent types.
|
||||
// TODO: is there a better name than EqualityInvariant
|
||||
@@ -193,6 +246,59 @@ func (obj *EqualityInvariant) Matches(solved map[interfaces.Expr]*types.Type) (b
|
||||
return true, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
func (obj *EqualityInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// The idea here is that we look for the expression pointers in the list
|
||||
// of partial invariants. It's only impossible if we (1) find both of
|
||||
// them, and (2) that they relate to each other. The second part is
|
||||
// harder.
|
||||
var one, two bool
|
||||
exprs := []interfaces.Invariant{}
|
||||
for _, x := range partials {
|
||||
for _, y := range x.ExprList() { // []interfaces.Expr
|
||||
if y == obj.Expr1 {
|
||||
one = true
|
||||
exprs = append(exprs, x)
|
||||
}
|
||||
if y == obj.Expr2 {
|
||||
two = true
|
||||
exprs = append(exprs, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !one || !two {
|
||||
return nil // we're unconnected to anything, this is possible!
|
||||
}
|
||||
|
||||
// we only need to check the connections in this case...
|
||||
// let's keep this simple, and less perfect for now...
|
||||
var typ *types.Type
|
||||
for _, x := range exprs {
|
||||
eq, ok := x.(*EqualsInvariant)
|
||||
if !ok {
|
||||
// XXX: add support for other kinds in the future...
|
||||
continue
|
||||
}
|
||||
|
||||
if typ != nil {
|
||||
if err := typ.Cmp(eq.Type); err != nil {
|
||||
// we found proof it's not possible
|
||||
return errwrap.Wrapf(err, "not possible")
|
||||
}
|
||||
}
|
||||
|
||||
typ = eq.Type // store for next type
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EqualityInvariantList is an invariant that symbolizes that all the
|
||||
// expressions listed must have equivalent types.
|
||||
type EqualityInvariantList struct {
|
||||
@@ -234,6 +340,62 @@ func (obj *EqualityInvariantList) Matches(solved map[interfaces.Expr]*types.Type
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
func (obj *EqualityInvariantList) Possible(partials []interfaces.Invariant) error {
|
||||
// The idea here is that we look for the expression pointers in the list
|
||||
// of partial invariants. It's only impossible if we (1) find two or
|
||||
// more, and (2) that any of them relate to each other. The second part
|
||||
// is harder.
|
||||
inList := func(needle interfaces.Expr, haystack []interfaces.Expr) bool {
|
||||
for _, x := range haystack {
|
||||
if x == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
exprs := []interfaces.Invariant{}
|
||||
for _, x := range partials {
|
||||
for _, y := range x.ExprList() { // []interfaces.Expr
|
||||
if inList(y, obj.Exprs) {
|
||||
exprs = append(exprs, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(exprs) <= 1 {
|
||||
return nil // we're unconnected to anything, this is possible!
|
||||
}
|
||||
|
||||
// we only need to check the connections in this case...
|
||||
// let's keep this simple, and less perfect for now...
|
||||
var typ *types.Type
|
||||
for _, x := range exprs {
|
||||
eq, ok := x.(*EqualsInvariant)
|
||||
if !ok {
|
||||
// XXX: add support for other kinds in the future...
|
||||
continue
|
||||
}
|
||||
|
||||
if typ != nil {
|
||||
if err := typ.Cmp(eq.Type); err != nil {
|
||||
// we found proof it's not possible
|
||||
return errwrap.Wrapf(err, "not possible")
|
||||
}
|
||||
}
|
||||
|
||||
typ = eq.Type // store for next type
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EqualityWrapListInvariant expresses that a list in Expr1 must have elements
|
||||
// that have the same type as the expression in Expr2Val.
|
||||
type EqualityWrapListInvariant struct {
|
||||
@@ -268,6 +430,18 @@ func (obj *EqualityWrapListInvariant) Matches(solved map[interfaces.Expr]*types.
|
||||
return true, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *EqualityWrapListInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// XXX: not implemented
|
||||
return nil // safer to return nil than error
|
||||
}
|
||||
|
||||
// EqualityWrapMapInvariant expresses that a map in Expr1 must have keys that
|
||||
// match the type of the expression in Expr2Key and values that match the type
|
||||
// of the expression in Expr2Val.
|
||||
@@ -290,7 +464,7 @@ func (obj *EqualityWrapMapInvariant) ExprList() []interfaces.Expr {
|
||||
// Matches returns whether an invariant matches the existing solution. If it is
|
||||
// inconsistent, then it errors.
|
||||
func (obj *EqualityWrapMapInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool, error) {
|
||||
t1, exists1 := solved[obj.Expr1] // list type
|
||||
t1, exists1 := solved[obj.Expr1] // map type
|
||||
t2, exists2 := solved[obj.Expr2Key]
|
||||
t3, exists3 := solved[obj.Expr2Val]
|
||||
if !exists1 || !exists2 || !exists3 {
|
||||
@@ -308,6 +482,18 @@ func (obj *EqualityWrapMapInvariant) Matches(solved map[interfaces.Expr]*types.T
|
||||
return true, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *EqualityWrapMapInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// XXX: not implemented
|
||||
return nil // safer to return nil than error
|
||||
}
|
||||
|
||||
// EqualityWrapStructInvariant expresses that a struct in Expr1 must have fields
|
||||
// that match the type of the expressions listed in Expr2Map.
|
||||
type EqualityWrapStructInvariant struct {
|
||||
@@ -344,7 +530,7 @@ func (obj *EqualityWrapStructInvariant) ExprList() []interfaces.Expr {
|
||||
// Matches returns whether an invariant matches the existing solution. If it is
|
||||
// inconsistent, then it errors.
|
||||
func (obj *EqualityWrapStructInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool, error) {
|
||||
t1, exists1 := solved[obj.Expr1] // list type
|
||||
t1, exists1 := solved[obj.Expr1] // struct type
|
||||
if !exists1 {
|
||||
return false, nil // not matched yet
|
||||
}
|
||||
@@ -375,6 +561,18 @@ func (obj *EqualityWrapStructInvariant) Matches(solved map[interfaces.Expr]*type
|
||||
return found, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *EqualityWrapStructInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// XXX: not implemented
|
||||
return nil // safer to return nil than error
|
||||
}
|
||||
|
||||
// EqualityWrapFuncInvariant expresses that a func in Expr1 must have args that
|
||||
// match the type of the expressions listed in Expr2Map and a return value that
|
||||
// matches the type of the expression in Expr2Out.
|
||||
@@ -399,7 +597,7 @@ func (obj *EqualityWrapFuncInvariant) String() string {
|
||||
}
|
||||
s[i] = fmt.Sprintf("%s %p", k, t)
|
||||
}
|
||||
return fmt.Sprintf("%p == func{%s} %p", obj.Expr1, strings.Join(s, "; "), obj.Expr2Out)
|
||||
return fmt.Sprintf("%p == func(%s) %p", obj.Expr1, strings.Join(s, "; "), obj.Expr2Out)
|
||||
}
|
||||
|
||||
// ExprList returns the list of valid expressions in this invariant.
|
||||
@@ -415,7 +613,7 @@ func (obj *EqualityWrapFuncInvariant) ExprList() []interfaces.Expr {
|
||||
// Matches returns whether an invariant matches the existing solution. If it is
|
||||
// inconsistent, then it errors.
|
||||
func (obj *EqualityWrapFuncInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool, error) {
|
||||
t1, exists1 := solved[obj.Expr1] // list type
|
||||
t1, exists1 := solved[obj.Expr1] // func type
|
||||
if !exists1 {
|
||||
return false, nil // not matched yet
|
||||
}
|
||||
@@ -454,6 +652,72 @@ func (obj *EqualityWrapFuncInvariant) Matches(solved map[interfaces.Expr]*types.
|
||||
return found, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *EqualityWrapFuncInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// XXX: not implemented
|
||||
return nil // safer to return nil than error
|
||||
}
|
||||
|
||||
// EqualityWrapCallInvariant expresses that a call result that happened in Expr1
|
||||
// must match the type of the function result listed in Expr2. In this case,
|
||||
// Expr2 will be a function expression, and the returned expression should match
|
||||
// with the Expr1 expression, when comparing types.
|
||||
// TODO: should this be named EqualityWrapFuncInvariant or not?
|
||||
// TODO: should Expr1 and Expr2 be reversed???
|
||||
type EqualityWrapCallInvariant struct {
|
||||
Expr1 interfaces.Expr
|
||||
Expr2Func interfaces.Expr
|
||||
}
|
||||
|
||||
// String returns a representation of this invariant.
|
||||
func (obj *EqualityWrapCallInvariant) String() string {
|
||||
return fmt.Sprintf("%p == call(%p)", obj.Expr1, obj.Expr2Func)
|
||||
}
|
||||
|
||||
// ExprList returns the list of valid expressions in this invariant.
|
||||
func (obj *EqualityWrapCallInvariant) ExprList() []interfaces.Expr {
|
||||
return []interfaces.Expr{obj.Expr1, obj.Expr2Func}
|
||||
}
|
||||
|
||||
// Matches returns whether an invariant matches the existing solution. If it is
|
||||
// inconsistent, then it errors.
|
||||
func (obj *EqualityWrapCallInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool, error) {
|
||||
t1, exists1 := solved[obj.Expr1] // call type
|
||||
t2, exists2 := solved[obj.Expr2Func]
|
||||
if !exists1 || !exists2 {
|
||||
return false, nil // not matched yet
|
||||
}
|
||||
//if t1.Kind != types.KindFunc {
|
||||
// return false, fmt.Errorf("expected func kind")
|
||||
//}
|
||||
|
||||
if t2.Kind != types.KindFunc {
|
||||
return false, fmt.Errorf("expected func kind")
|
||||
}
|
||||
if err := t1.Cmp(t2.Out); err != nil {
|
||||
return false, err // inconsistent!
|
||||
}
|
||||
return true, nil // matched!
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *EqualityWrapCallInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
// XXX: not implemented
|
||||
return nil // safer to return nil than error
|
||||
}
|
||||
|
||||
// ConjunctionInvariant represents a list of invariants which must all be true
|
||||
// together. In other words, it's a grouping construct for a set of invariants.
|
||||
type ConjunctionInvariant struct {
|
||||
@@ -495,6 +759,24 @@ func (obj *ConjunctionInvariant) Matches(solved map[interfaces.Expr]*types.Type)
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *ConjunctionInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
for _, invar := range obj.Invariants {
|
||||
if err := invar.Possible(partials); err != nil {
|
||||
// we found proof it's not possible
|
||||
return errwrap.Wrapf(err, "not possible")
|
||||
}
|
||||
}
|
||||
// XXX: unfortunately we didn't look for them all together with a solver
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExclusiveInvariant represents a list of invariants where one and *only* one
|
||||
// should hold true. To combine multiple invariants in one of the list elements,
|
||||
// you can group multiple invariants together using a ConjunctionInvariant. Do
|
||||
@@ -538,9 +820,11 @@ func (obj *ExclusiveInvariant) ExprList() []interfaces.Expr {
|
||||
func (obj *ExclusiveInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool, error) {
|
||||
found := false
|
||||
reterr := fmt.Errorf("all exclusives errored")
|
||||
var errs error
|
||||
for _, invar := range obj.Invariants {
|
||||
match, err := invar.Matches(solved)
|
||||
if err != nil {
|
||||
errs = errwrap.Append(errs, err)
|
||||
continue
|
||||
}
|
||||
if !match {
|
||||
@@ -560,7 +844,65 @@ func (obj *ExclusiveInvariant) Matches(solved map[interfaces.Expr]*types.Type) (
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, reterr
|
||||
return false, errwrap.Wrapf(reterr, errwrap.String(errs))
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation is currently not implemented!
|
||||
func (obj *ExclusiveInvariant) Possible(partials []interfaces.Invariant) error {
|
||||
var errs error
|
||||
for _, invar := range obj.Invariants {
|
||||
err := invar.Possible(partials)
|
||||
if err == nil {
|
||||
// we found proof it's possible
|
||||
return nil
|
||||
}
|
||||
errs = errwrap.Append(errs, err)
|
||||
}
|
||||
|
||||
return errwrap.Wrapf(errs, "not possible")
|
||||
}
|
||||
|
||||
// simplify attempts to reduce the exclusive invariant to eliminate any
|
||||
// possibilities based on the list of known partials at this time. Hopefully,
|
||||
// this will weed out some of the function polymorphism possibilities so that we
|
||||
// can solve the problem without recursive, combinatorial permutation, which is
|
||||
// very, very slow.
|
||||
func (obj *ExclusiveInvariant) simplify(partials []interfaces.Invariant) ([]interfaces.Invariant, error) {
|
||||
if len(obj.Invariants) == 0 { // unexpected case
|
||||
return []interfaces.Invariant{}, nil // we don't need anything!
|
||||
}
|
||||
|
||||
possible := []interfaces.Invariant{}
|
||||
var reasons error
|
||||
for _, invar := range obj.Invariants { // []interfaces.Invariant
|
||||
if err := invar.Possible(partials); err != nil {
|
||||
reasons = errwrap.Append(reasons, err)
|
||||
continue
|
||||
}
|
||||
possible = append(possible, invar)
|
||||
}
|
||||
|
||||
if len(possible) == 0 { // nothing was possible
|
||||
return nil, errwrap.Wrapf(reasons, "no possible simplifications")
|
||||
}
|
||||
if len(possible) == 1 { // we flattened out the exclusive!
|
||||
return possible, nil
|
||||
}
|
||||
|
||||
if len(possible) == len(obj.Invariants) { // nothing changed
|
||||
return nil, fmt.Errorf("no possible simplifications, we're unchanged")
|
||||
}
|
||||
|
||||
invar := &ExclusiveInvariant{
|
||||
Invariants: possible, // hopefully a smaller exclusive!
|
||||
}
|
||||
return []interfaces.Invariant{invar}, nil
|
||||
}
|
||||
|
||||
// exclusivesProduct returns a list of different products produced from the
|
||||
@@ -627,6 +969,18 @@ func (obj *AnyInvariant) Matches(solved map[interfaces.Expr]*types.Type) (bool,
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// Possible returns an error if it is certain that it is NOT possible to get a
|
||||
// solution with this invariant and the set of partials. In certain cases, it
|
||||
// might not be able to determine that it's not possible, while simultaneously
|
||||
// not being able to guarantee a possible solution either. In this situation, it
|
||||
// should return nil, since this is used as a filtering mechanism, and the nil
|
||||
// result of possible is preferred over eliminating a tricky, but possible one.
|
||||
// This particular implementation always returns nil.
|
||||
func (obj *AnyInvariant) Possible([]interfaces.Invariant) error {
|
||||
// keep it simple, even though we don't technically check the inputs...
|
||||
return nil
|
||||
}
|
||||
|
||||
// InvariantSolution lists a trivial set of EqualsInvariant mappings so that you
|
||||
// can populate your AST with SetType calls in a simple loop.
|
||||
type InvariantSolution struct {
|
||||
|
||||
Reference in New Issue
Block a user