| 426 | } |
| 427 | |
| 428 | func newBoundsAnalyzer(programInfo *ProgramInfo, nameTrie symbols.NameTrie, initialFacts []ast.Atom, rulesMap map[ast.PredicateSym][]ast.Clause) (*BoundsAnalyzer, error) { |
| 429 | var err error |
| 430 | relTypeMap := make(map[ast.PredicateSym]ast.BaseTerm) |
| 431 | |
| 432 | initialFactTypes := make(map[ast.PredicateSym]map[uint64]ast.BaseTerm) |
| 433 | for _, f := range initialFacts { |
| 434 | // From a unit clause (initial fact) `foo(2, 'a')` we |
| 435 | // derive an "observation" [/int /string]. |
| 436 | observation := make([]ast.BaseTerm, len(f.Args)) |
| 437 | for i, arg := range f.Args { |
| 438 | observation[i] = boundOfArg(arg, nil, nameTrie) |
| 439 | } |
| 440 | relType := symbols.NewRelType(observation...) |
| 441 | m, ok := initialFactTypes[f.Predicate] |
| 442 | if !ok { |
| 443 | m = make(map[uint64]ast.BaseTerm) |
| 444 | initialFactTypes[f.Predicate] = m |
| 445 | } |
| 446 | m[relType.Hash()] = relType |
| 447 | } |
| 448 | |
| 449 | // We gather all relation types. |
| 450 | initialFactMap := make(map[ast.PredicateSym]ast.BaseTerm, len(initialFactTypes)) |
| 451 | for pred, relTypeMap := range initialFactTypes { |
| 452 | relTypes := make([]ast.BaseTerm, 0, len(relTypeMap)) |
| 453 | for _, relType := range relTypeMap { |
| 454 | relTypes = append(relTypes, relType) |
| 455 | } |
| 456 | if len(relTypes) == 1 { |
| 457 | initialFactMap[pred] = relTypes[0] |
| 458 | } else { |
| 459 | initialFactMap[pred] = symbols.NewUnionType(relTypes...) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | for _, decl := range programInfo.Decls { |
| 464 | if decl.IsSynthetic() && !decl.IsExtensional() { |
| 465 | continue |
| 466 | } |
| 467 | // Populate relTypes with type info from declarations. |
| 468 | // For intensional predicates, we include only user-supplied declaration. |
| 469 | // For extensional predicates, we include declarations whether or not they |
| 470 | // are synthetic. |
| 471 | pred := decl.DeclaredAtom.Predicate |
| 472 | relTypeMap[pred], err = symbols.RelTypeExprFromDecl(*programInfo.Decls[pred]) |
| 473 | if err != nil { |
| 474 | return nil, err |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | // Populate relTypes with all builtin relation types. |
| 479 | for pred, relTypeExpr := range symbols.BuiltinRelations { |
| 480 | relTypeMap[pred] = relTypeExpr |
| 481 | } |
| 482 | |
| 483 | visiting := make(map[ast.PredicateSym]bool) |
| 484 | return &BoundsAnalyzer{ |
| 485 | programInfo, nameTrie, rulesMap, relTypeMap, initialFactMap, |