/// <summary> /// Backtracks to the current choice point /// </summary> public void BacktrackToChoicePoint() { // Restore the environment permanent variables if (!ReferenceEquals(_choicePoint.Environment, _environment)) { for (var varIndex = 0; varIndex < _choicePoint.Environment.Variables.Length; ++varIndex) { _registers[varIndex] = _choicePoint.Environment.Variables[varIndex]; } for (var varIndex = _choicePoint.Environment.Variables.Length; varIndex < _environment.Variables.Length; ++varIndex) { _registers[varIndex] = new SimpleReference(); } } // Restore the argument registers var argumentIndex = _choicePoint.Environment.Variables.Length; foreach (var argument in _choicePoint.Arguments) { _registers[argumentIndex].SetTo(argument); ++argumentIndex; } // Environment is reset to the choice point environment _environment = _choicePoint.Environment; // Reset the trail _choicePoint.Trail.Reset(); _trail = _choicePoint.Trail; }
protected SimpleReference Add(String campoBaseOrigem, String campoBaseDestino) { SimpleReference reference = new SimpleReference(campoBaseOrigem, campoBaseDestino); mSimpleReference.Add(reference); return(reference); }
public void RES_failingVerificationWithCyclicDependencyException() { if ((GetComponentAdapterNature() & RESOLVING) > 0) { Hashtable cycleInstances = new Hashtable(); IObjectReference cycleCheck = new SimpleReference(); object[] wrapperDependencies = new Object[] { cycleInstances, cycleCheck }; IMutablePicoContainer picoContainer = new DefaultPicoContainer(CreateDefaultComponentAdapterFactory()); IComponentAdapter componentAdapter = prepRES_failingVerificationWithCyclicDependencyException(picoContainer); Assert.AreSame(GetComponentAdapterType(), componentAdapter.GetType()); Assert.IsTrue(picoContainer.ComponentAdapters.Contains(componentAdapter)); IPicoContainer wrappedPicoContainer = WrapComponentInstances(typeof(CycleDetectorComponentAdapter), picoContainer, wrapperDependencies); try { componentAdapter.Verify(wrappedPicoContainer); Assert.Fail("Thrown PicoVerificationException excpected"); } catch (CyclicDependencyException cycle) { object[] dependencies = cycle.Dependencies; Assert.AreSame(dependencies[0], dependencies[dependencies.Length - 1]); } } }
protected SimpleReference Add(String campoBaseOrigem, String campoBaseDestino, IConverter converter) { SimpleReference reference = new SimpleReference(campoBaseOrigem, campoBaseDestino); reference.mConverter = converter; mSimpleReference.Add(reference); return(reference); }
public override StoredProcedureResult Generate() { var delim = "," + Environment.NewLine; var queryKey = _byKey; if (_byKey.HasReference && _byKey.Reference.IsReferenceToHiddenPrimaryKey) { queryKey = queryKey.Reference.TargetAtomAlternateKey; } string sprocSuffix = _isUnique ? $"GetOneBy{queryKey.Name}" : $"GetBy{queryKey.Name}"; string Schema = Atom.AdditionalInfo.Schema, Params = GetTypedSprocParam(queryKey), TableName = Atom.Name, Key = queryKey.Name; var plan = new QueryPlan { QueryMembers = Atom.Members.Where(IsQueryableColumn).Select(AliasedAtomMemberInfo.FromAtomMemberInfo), References = { new SimpleReference(Atom) }, Filters = { new AtomFilter { FilterValue = "@" + Key, Member = queryKey } } }; if (queryKey != _byKey) { var simpleRef = new SimpleReference(queryKey.Atom); plan.References = new List <Reference> { simpleRef, new ResolvedReference(Atom, new List <Reference> { simpleRef }) }; } var template = GenerateQuerySproc(Schema, TableName, sprocSuffix, Params, plan); var name = $"{Schema}.{TableName}_{sprocSuffix}"; return(new StoredProcedureResult { Name = name, Sql = template, AccessorMetadata = new SqlAccessorMetadata { BaseAtom = ProjectedAtomRoot.FromAtom(Atom), QueryType = _isUnique ? QueryType.GetOne : QueryType.GetBy, QueryKey = queryKey, Name = name } }); }
private IMongoQuery HandleEndsWith(SimpleReference reference, SimpleFunction function) { if (!(function.Args[0] is string)) { throw new InvalidOperationException("StartsWith can only be used with a string."); } return(Query.Matches((string)FormatObject(reference), new BsonRegularExpression(".*" + (string)function.Args[0] + "$"))); }
private ODataExpression Convert(SimpleReference reference) { var formattedReference = reference.GetAliasOrName(); if (reference is ObjectReference) { formattedReference = string.Join(".", (reference as ObjectReference).GetAllObjectNames().Skip(1)); } return ODataDynamic.ExpressionFromReference(formattedReference); }
public override StoredProcedureResult Generate() { var delim = "," + Environment.NewLine; var queryKey = _byKey; if (_byKey.HasReference && _byKey.Reference.IsReferenceToHiddenPrimaryKey) { queryKey = queryKey.Reference.TargetAtomAlternateKey; } string sprocSuffix = _isUnique ? $"GetOneBy{queryKey.Name}" : $"GetBy{queryKey.Name}" ; string Schema = Atom.AdditionalInfo.Schema, Params = GetTypedSprocParam(queryKey), TableName = Atom.Name, Key = queryKey.Name; var plan = new QueryPlan { QueryMembers = Atom.Members.Where(IsQueryableColumn).Select(AliasedAtomMemberInfo.FromAtomMemberInfo), References = { new SimpleReference(Atom) }, Filters = { new AtomFilter { FilterValue = "@" + Key, Member = queryKey } } }; if (queryKey != _byKey) { var simpleRef = new SimpleReference(queryKey.Atom); plan.References = new List<Reference> { simpleRef, new ResolvedReference(Atom, new List<Reference> { simpleRef }) }; } var template = GenerateQuerySproc(Schema, TableName, sprocSuffix, Params, plan); var name = $"{Schema}.{TableName}_{sprocSuffix}"; return new StoredProcedureResult { Name = name, Sql = template, AccessorMetadata = new SqlAccessorMetadata { BaseAtom = ProjectedAtomRoot.FromAtom(Atom), QueryType = _isUnique ? QueryType.GetOne : QueryType.GetBy, QueryKey = queryKey, Name = name } }; }
private ODataExpression Convert(SimpleReference reference) { var formattedReference = reference.GetAliasOrName(); if (reference is ObjectReference) { formattedReference = string.Join(".", (reference as ObjectReference).GetAllObjectNames().Skip(1)); } return(ODataDynamic.ExpressionFromReference(formattedReference)); }
public ByteCodeEnvironment(int numVariables, int numArguments, ByteCodeEnvironment continuationEnvironment) { Variables = new SimpleReference[numVariables]; NumberOfArguments = numArguments; for (var x = 0; x < numVariables; ++x) { Variables[x] = new SimpleReference(); } ContinuationEnvironment = continuationEnvironment; ContinuationPointer = -1; }
private string FormatColumnClause(SimpleReference reference, bool excludeAlias) { var formatted = TryFormatAsObjectReference(reference as ObjectReference, excludeAlias) ?? TryFormatAsFunctionReference(reference as FunctionReference, excludeAlias) ?? TryFormatAsMathReference(reference as MathReference, excludeAlias); if (formatted != null) return formatted; throw new InvalidOperationException("SimpleReference type not supported."); }
public static ValueResolver Create(SimpleReference reference) { var objectReference = reference as ObjectReference; if (!ReferenceEquals(null, objectReference)) return new ObjectValueResolver(objectReference); var functionReference = reference as FunctionReference; if (!ReferenceEquals(null, functionReference)) { if (FunctionHandlers.Exists(functionReference.Name)) return new AggregateValueResolver(functionReference); return new FunctionValueResolver(functionReference); } throw new InvalidOperationException("Unresolvable Reference type."); }
private IMongoQuery HandleLike(SimpleReference reference, SimpleFunction function) { if (function.Args[0] is Regex) { return(Query.Matches((string)FormatObject(reference), new BsonRegularExpression((Regex)function.Args[0]))); } else if (function.Args[0] is string) { return(Query.Matches((string)FormatObject(reference), new BsonRegularExpression((string)FormatObject(function.Args[0])))); } throw new InvalidOperationException("Like can only be used with a string or Regex."); }
/// <summary> /// Stores a new reference in two variables and the current structure /// </summary> private void PutVariable(int variable, int argument) { var newValue = new SimpleReference(); // Store in the variables _registers[variable].SetTo(newValue); _registers[argument].SetTo(newValue); // Store to the current structure if (_lastArgument != null) { _lastArgument.SetTo(newValue); _lastArgument = _lastArgument.NextArgument; } }
public string FormatColumnClause(SimpleReference reference) { var formatted = TryFormatAsObjectReference(reference as ObjectReference) ?? TryFormatAsFunctionReference(reference as FunctionReference) ?? TryFormatAsMathReference(reference as MathReference); if (formatted != null) { return(formatted); } throw new InvalidOperationException("SimpleReference type not supported."); }
/// <summary> /// Either begins unifying against an existing structure (if the variable is bound) or /// begins writing a new structure to an unbound variable. /// </summary> private bool GetStructure(int literal, int variable, int termLength) { var termName = _literals[literal]; // Get the dereferenced address of the variable var heapValue = _registers[variable].Dereference(); // Action depends on what's at that address if (heapValue.IsVariable()) { // Variable is an unbound ref cell: bind it to a new value that we create ArgumentReference firstArgument = null; for (int argNum = 0; argNum < termLength; ++argNum) { var newArgument = new ArgumentReference(null, firstArgument); firstArgument = newArgument; } var newStructure = new SimpleReference(termName, firstArgument); _lastArgument = firstArgument; _structurePtr = firstArgument; Bind(heapValue, newStructure); _writeMode = true; } else if (!heapValue.IsReference()) { if (Equals(heapValue.Term, termName)) { // Set the structure pointer, and use read mode _structurePtr = heapValue.Reference; _writeMode = false; } else { // Structure doesn't match; fail return(false); } } else { // Fail return(false); } return(true); }
private string FormatColumnClause(SimpleReference reference, bool excludeAlias) { var formatted = TryFormatAsObjectReference(reference as ObjectReference, excludeAlias) ?? TryFormatAsFunctionReference(reference as FunctionReference, excludeAlias) ?? TryFormatAsMathReference(reference as MathReference, excludeAlias) ?? TryFormatAsAllColumnsReference(reference as AllColumnsSpecialReference, excludeAlias); if (formatted != null) { return(formatted); } throw new InvalidOperationException("SimpleReference type not supported."); }
/// <summary> /// Allocates space for a number of permanent and argument variables. /// </summary> /// <remarks> /// Permanent variables are stored in the environment and are numbered from 0. /// Arguments occur after the temporary variables and have their values preserved /// from the previous state by this call. /// </remarks> private void Allocate(int numPermanent, int numArguments) { // Allocate a new environment var newEnvironment = new ByteCodeEnvironment(numPermanent, numArguments, _environment); newEnvironment.ContinuationEnvironment = _environment; // Make sure that we don't overwrite arguments in the previous environment by replacing them with new temporary variables if (numPermanent + numArguments < _environment.Variables.Length) { for (int oldPermanent = numPermanent + numArguments; oldPermanent < _environment.Variables.Length; ++oldPermanent) { _registers[oldPermanent] = new SimpleReference(); } } // Move arguments to their new position int oldArgStart = _environment.Variables.Length; if (oldArgStart > numPermanent) { // Moving arguments 'down', leaving a hole for (int argument = 0; argument < numArguments; ++argument) { _registers[argument + numPermanent] = _registers[argument + oldArgStart]; _registers[argument + oldArgStart] = new SimpleReference(); } } else if (oldArgStart < numPermanent) { // Moving arguments 'up', old locations will be overwritten by new permanent variables for (int argument = numArguments - 1; argument >= 0; --argument) { _registers[argument + numPermanent] = _registers[argument + oldArgStart]; } } // Copy in the new permanent variables for (int permanent = 0; permanent < numPermanent; ++permanent) { _registers[permanent] = newEnvironment.Variables[permanent]; } _environment = newEnvironment; }
public ByteCodeExecutor(ByteCodePoint[] program, ILiteral[] literals, int maxVariableIndex) { if (program == null) { throw new ArgumentNullException(nameof(program)); } _program = program; _literals = literals; _programCounter = 0; _environment = new ByteCodeEnvironment(0, 0, null); _registers = new SimpleReference[maxVariableIndex]; for (var registerIndex = 0; registerIndex < _registers.Length; ++registerIndex) { _registers[registerIndex] = new SimpleReference(); } }
private string FormatGroupByColumnClause(SimpleReference reference) { var objectReference = reference as ObjectReference; if (!ReferenceEquals(objectReference, null)) { var table = _schema.FindTable(objectReference.GetOwner().GetName()); var column = table.FindColumn(objectReference.GetName()); return(string.Format("{0}.{1}", table.QualifiedName, column.QuotedName)); } var functionReference = reference as FunctionReference; if (!ReferenceEquals(functionReference, null)) { return(FormatGroupByColumnClause(functionReference.Argument)); } throw new InvalidOperationException("SimpleReference type not supported."); }
/// <summary> /// Cretes a new reference and stores it in the current structure and a particular variable /// </summary> private void SetVariable(int variable) { // Create a new reference IReferenceLiteral newReference; // Add to the current structure if (_lastArgument != null) { // The last argument is the reference newReference = _lastArgument; _lastArgument = _lastArgument.NextArgument; } else { newReference = new SimpleReference(); } // Store in the variable _registers[variable].SetTo(newReference); }
/// <summary> /// Generates a new empty structure of a particular length on the heap and stores a reference /// to it in a variable /// </summary> private void PutStructure(int termLiteral, int variable, int termLength) { var termName = _literals[termLiteral]; // Create the structure ArgumentReference firstArgument = null; for (int argNum = 0; argNum < termLength; ++argNum) { var newArgument = new ArgumentReference(null, firstArgument); firstArgument = newArgument; } var structure = new SimpleReference(termName, firstArgument); _lastArgument = firstArgument; // Store in the variable _registers[variable].SetTo(structure); }
private static List <Reference> ResolveReferences(Queue <AtomModel> sortedReferences, HashSet <AtomModel> projectedAtoms) { // Pick the first ref to be the atomModel var primaryRef = new SimpleReference(sortedReferences.Dequeue()); var references = new List <Reference> { primaryRef }; var referenceMap = new Dictionary <string, Reference> { { primaryRef.Name, primaryRef } }; var atomDependencyMap = projectedAtoms.ToDictionary(atom => atom.Name, atom => atom.GetDependencies()); foreach (var atomRelation in sortedReferences) { var posibleReferences = atomDependencyMap[atomRelation.Name]; if (!posibleReferences.Any()) { var r = new SimpleReference(atomRelation); references.Add(r); referenceMap.Add(r.Name, r); } else { var referenceName = posibleReferences.First(referenceMap.ContainsKey); var reference = referenceMap[referenceName]; var resolvedDependencies = posibleReferences.Where(referenceMap.ContainsKey) .Select(p => referenceMap[p]); var r = new ResolvedReference(atomRelation, resolvedDependencies); references.Add(r); referenceMap.Add(r.Name, r); } } return(references); }
public static ValueResolver Create(SimpleReference reference) { var objectReference = reference as ObjectReference; if (!ReferenceEquals(null, objectReference)) { return(new ObjectValueResolver(objectReference)); } var functionReference = reference as FunctionReference; if (!ReferenceEquals(null, functionReference)) { if (FunctionHandlers.Exists(functionReference.Name)) { return(new AggregateValueResolver(functionReference)); } return(new FunctionValueResolver(functionReference)); } throw new InvalidOperationException("Unresolvable Reference type."); }
public async Task SolveSimplePredicate() { // Knowledge is a(x) var a = Literal.NewFunctor(1); var x = Literal.NewAtom(); var aOfX = a.With(x); var knowledge = KnowledgeBase.New().Assert(Clause.Always(aOfX)); // Generate a bytecode solver for this var solver = new ByteCodeSolver(); await solver.Compile(knowledge); // Call it with the query a(Y) var refToY = new SimpleReference(); var solve = solver.Call(a, refToY); var solved = solve(); Assert.IsTrue(solved); Assert.AreEqual(x, refToY.Term); }
/// <summary> /// Deallocates the last allocated block, restoring the permanent variables from the preceding environment /// </summary> private void Deallocate() { var oldEnvironment = _environment.ContinuationEnvironment; if (oldEnvironment == null) { return; } // Restore any permanent variables from the new environment for (var varIndex = 0; varIndex < oldEnvironment.Variables.Length; ++varIndex) { _registers[varIndex] = oldEnvironment.Variables[varIndex]; } // Reallocate any temporary variables that have newly appeared for (var varIndex = oldEnvironment.Variables.Length; varIndex < _environment.Variables.Length; ++varIndex) { _registers[varIndex] = new SimpleReference(); } // Finally, restore the environment _environment = oldEnvironment; }
private static bool ReferenceIsNotAggregateFunction(SimpleReference reference) { var functionReference = reference as FunctionReference; return ReferenceEquals(functionReference, null) || !FunctionHandlers.Exists(functionReference.Name); }
public string FormatColumnClauseWithoutAlias(SimpleReference reference) { return FormatColumnClause(reference, true); }
public string FormatColumnClause(SimpleReference reference) { return FormatColumnClause(reference, false); }
internal protected string FormatReference(SimpleReference reference) { return(_simpleReferenceFormatter.FormatColumnClause(reference)); }
private string FormatGroupByColumnClause(SimpleReference reference) { var objectReference = reference as ObjectReference; if (!ReferenceEquals(objectReference, null)) { var table = _schema.FindTable(objectReference.GetOwner().GetName()); var column = table.FindColumn(objectReference.GetName()); return string.Format("{0}.{1}", table.QualifiedName, column.QuotedName); } var functionReference = reference as FunctionReference; if (!ReferenceEquals(functionReference, null)) { return FormatGroupByColumnClause(functionReference.Argument); } throw new InvalidOperationException("SimpleReference type not supported."); }
private static List<Reference> ResolveReferences(Queue<AtomModel> sortedReferences, HashSet<AtomModel> projectedAtoms) { // Pick the first ref to be the atomModel var primaryRef = new SimpleReference(sortedReferences.Dequeue()); var references = new List<Reference> { primaryRef }; var referenceMap = new Dictionary<string, Reference> { { primaryRef.Name, primaryRef } }; var atomDependencyMap = projectedAtoms.ToDictionary(atom => atom.Name, atom => atom.GetDependencies()); foreach (var atomRelation in sortedReferences) { var posibleReferences = atomDependencyMap[atomRelation.Name]; if (!posibleReferences.Any()) { var r = new SimpleReference(atomRelation); references.Add(r); referenceMap.Add(r.Name, r); } else { var referenceName = posibleReferences.First(referenceMap.ContainsKey); var reference = referenceMap[referenceName]; var resolvedDependencies = posibleReferences.Where(referenceMap.ContainsKey) .Select(p => referenceMap[p]); var r = new ResolvedReference(atomRelation, resolvedDependencies); references.Add(r); referenceMap.Add(r.Name, r); } } return references; }
internal protected string FormatReference(SimpleReference reference) { return _simpleReferenceFormatter.FormatColumnClause(reference); }
private string FormatSelectItem(Table table, SimpleReference item) { return table.FindColumn(item.GetAliasOrName()).ActualName; }
private static bool ReferenceIsNotAggregateFunction(SimpleReference reference) { var functionReference = reference as FunctionReference; return(ReferenceEquals(functionReference, null) || !FunctionHandlers.Exists(functionReference.Name)); }
private QueryComplete HandleEndsWith(SimpleReference reference, SimpleFunction function) { if (!(function.Args[0] is string)) throw new InvalidOperationException("StartsWith can only be used with a string."); return Query.Matches((string)FormatObject(reference), new BsonRegularExpression(".*" + (string)function.Args[0] + "$")); }
private QueryComplete HandleLike(SimpleReference reference, SimpleFunction function) { if (function.Args[0] is Regex) return Query.Matches((string)FormatObject(reference), new BsonRegularExpression((Regex)function.Args[0])); else if (function.Args[0] is string) return Query.Matches((string)FormatObject(reference), new BsonRegularExpression((string)FormatObject(function.Args[0]))); throw new InvalidOperationException("Like can only be used with a string or Regex."); }
public string FormatColumnClause(SimpleReference reference) { return(FormatColumnClause(reference, false)); }
public string FormatColumnClause(SimpleReference reference) { var formatted = TryFormatAsObjectReference(reference as ObjectReference) ?? TryFormatAsMathReference(reference as MathReference); if (formatted != null) return formatted; throw new InvalidOperationException("SimpleReference type not supported."); }
private string FormatSelectItem(Table table, SimpleReference item) { return(table.FindColumn(item.GetAliasOrName()).ActualName); }
public string FormatColumnClauseWithoutAlias(SimpleReference reference) { return(FormatColumnClause(reference, true)); }