public override void ApplyRhs(Match <Word, ShapeNode> targetMatch, Range <ShapeNode> range, VariableBindings varBindings) { ShapeNode curNode = range.End; foreach (PatternNode <Word, ShapeNode> node in _rhs.Children) { var constraint = (Constraint <Word, ShapeNode>)node; FeatureStruct fs = constraint.FeatureStruct.Clone(); if (varBindings != null) { fs.ReplaceVariables(varBindings); } curNode = targetMatch.Input.Shape.AddAfter(curNode, fs); if (IsIterative) { curNode.SetDirty(true); } } ShapeNode[] nodes = targetMatch.Input.Shape.GetNodes(range).ToArray(); for (int i = 0; i < _targetCount; i++) { nodes[i].SetDeleted(true); } MarkSuccessfulApply(targetMatch.Input); }
void IPhonologicalPatternSubruleSpec.ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode start = null, end = null; foreach (GroupCapture<ShapeNode> gc in targetMatch.GroupCaptures) { if (start == null || gc.Span.Start.CompareTo(start) < 0) start = gc.Span.Start; if (end == null || gc.Span.End.CompareTo(end) > 0) end = gc.Span.End; } Debug.Assert(start != null && end != null); GroupCapture<ShapeNode> leftGroup = targetMatch.GroupCaptures[_leftGroupName]; GroupCapture<ShapeNode> rightGroup = targetMatch.GroupCaptures[_rightGroupName]; foreach (Tuple<ShapeNode, ShapeNode> tuple in targetMatch.Input.Shape.GetNodes(leftGroup.Span).Zip(targetMatch.Input.Shape.GetNodes(rightGroup.Span))) { if (tuple.Item1.Type() != HCFeatureSystem.Segment || tuple.Item2.Type() != HCFeatureSystem.Segment) continue; FeatureStruct fs = tuple.Item1.Annotation.FeatureStruct.DeepClone(); tuple.Item1.Annotation.FeatureStruct.Union(tuple.Item2.Annotation.FeatureStruct); tuple.Item1.SetDirty(true); tuple.Item2.Annotation.FeatureStruct.Union(fs); tuple.Item2.SetDirty(true); } }
public override VCExpr VisitSelectOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result <VCExpr>() != null); OpTypesPair originalOpTypes = OriginalOpTypes(node); OpTypesPair newOpTypes; if (!NewOpCache.TryGetValue(originalOpTypes, out newOpTypes)) { MapType /*!*/ rawType = node[0].Type.AsMap; Contract.Assert(rawType != null); List <Type> /*!*/ abstractionInstantiation; Function /*!*/ select = AxBuilder.MapTypeAbstracter.Select(rawType, out abstractionInstantiation); Contract.Assert(abstractionInstantiation != null); newOpTypes = TypesPairForSelectStore(node, select, abstractionInstantiation); NewOpCache.Add(originalOpTypes, newOpTypes); } return(AssembleOpExpression(newOpTypes, node, bindings)); }
public void ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode start = null, end = null; foreach (GroupCapture<ShapeNode> gc in targetMatch.GroupCaptures) { if (start == null || gc.Span.Start.CompareTo(start) < 0) start = gc.Span.Start; if (end == null || gc.Span.End.CompareTo(end) > 0) end = gc.Span.End; } Debug.Assert(start != null && end != null); var morphs = targetMatch.Input.Morphs.Where(ann => ann.Span.Overlaps(start, end)) .Select(ann => new {Annotation = ann, Children = ann.Children.ToList()}).ToArray(); foreach (var morph in morphs) morph.Annotation.Remove(); GroupCapture<ShapeNode> leftGroup = targetMatch.GroupCaptures[_leftGroupName]; GroupCapture<ShapeNode> rightGroup = targetMatch.GroupCaptures[_rightGroupName]; ShapeNode beforeRightGroup = rightGroup.Span.Start.Prev; MoveNodesAfter(targetMatch.Input.Shape, leftGroup.Span.End, rightGroup.Span); MoveNodesAfter(targetMatch.Input.Shape, beforeRightGroup, leftGroup.Span); foreach (var morph in morphs) { Annotation<ShapeNode>[] children = morph.Children.OrderBy(ann => ann.Span).ToArray(); var newMorphAnn = new Annotation<ShapeNode>(_spanFactory.Create(children[0].Span.Start, children[children.Length - 1].Span.Start), morph.Annotation.FeatureStruct); newMorphAnn.Children.AddRange(morph.Children); targetMatch.Input.Annotations.Add(newMorphAnn, false); } }
public override bool Add(VariableBindings result) { foreach (int idx in varorder) { if (result.Variables[idx].LocalName != null && result.Values[idx] != null) { if (result.Values[idx].Uri != null) { Console.Write(result.Values[idx].Uri + " "); } else if (result.Values[idx] is Literal) { Console.Write(((Literal)result.Values[idx]).Value + " "); } else if (result.Values[idx] is BNode) { Console.Write("(bnode) "); } else { Console.Write(result.Values[idx] + " "); } } } Console.WriteLine(); return(true); }
/////////////////////////////////////////////////////////////////////////// public override VCExpr VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result <VCExpr>() != null); OpTypesPair originalOpTypes = OriginalOpTypes(node); OpTypesPair newOpTypes; if (!NewOpCache.TryGetValue(originalOpTypes, out newOpTypes)) { Function /*!*/ oriFun = ((VCExprBoogieFunctionOp)node.Op).Func; Contract.Assert(oriFun != null); List <Type /*!*/> /*!*/ inferredTypeArgs = new List <Type /*!*/>(); foreach (Type /*!*/ t in node.TypeArguments) { Contract.Assert(t != null); // inferredTypeArgs.Add(AxBuilder.MapTypeAbstracter.AbstractMapTypeRecursively(t)); inferredTypeArgs.Add(t); } VCExprOp /*!*/ newOp = Gen.BoogieFunctionOp(AxBuilderArguments.Typed2Untyped(oriFun)); newOpTypes = new OpTypesPair(newOp, inferredTypeArgs); NewOpCache.Add(originalOpTypes, newOpTypes); } return(AssembleOpExpression(newOpTypes, node, bindings)); }
private void _parse() { _requestId = new AsnObj(m_io, this, m_root); _errorStatus = new ErrorStatus(m_io, this, m_root); _errorIndex = new AsnObj(m_io, this, m_root); _variableBindings = new VariableBindings(m_io, this, m_root); }
private void CheckAccepting(Annotation <TOffset> ann, NullableValue <TOffset>[,] registers, TData output, VariableBindings varBindings, Arc <TData, TOffset> arc, ICollection <FstResult <TData, TOffset> > curResults, int[] priorities) { if (arc.Target.IsAccepting && (!_endAnchor || ann == _data.Annotations.GetEnd(_dir))) { var matchRegisters = (NullableValue <TOffset> [, ])registers.Clone(); ExecuteCommands(matchRegisters, arc.Target.Finishers, new NullableValue <TOffset>(), new NullableValue <TOffset>()); if (arc.Target.AcceptInfos.Count > 0) { foreach (AcceptInfo <TData, TOffset> acceptInfo in arc.Target.AcceptInfos) { var candidate = new FstResult <TData, TOffset>(acceptInfo.ID, matchRegisters, output.DeepClone(), varBindings.DeepClone(), acceptInfo.Priority, arc.Target.IsLazy, ann, priorities); if (acceptInfo.Acceptable == null || acceptInfo.Acceptable(_data, candidate)) { curResults.Add(candidate); } } } else { curResults.Add(new FstResult <TData, TOffset>(null, matchRegisters, output.DeepClone(), varBindings.DeepClone(), -1, arc.Target.IsLazy, ann, priorities)); } } }
public PhonologicalSubruleMatch(IPhonologicalPatternSubruleSpec subruleSpec, Range <ShapeNode> range, VariableBindings varBindings) { SubruleSpec = subruleSpec; Range = range; VariableBindings = varBindings; }
private void Untruncate(PatternNode <Word, ShapeNode> patternNode, Shape output, bool optional, VariableBindings varBindings) { foreach (PatternNode <Word, ShapeNode> node in patternNode.Children) { var constraint = node as Constraint <Word, ShapeNode>; if (constraint != null && constraint.Type() == HCFeatureSystem.Segment) { FeatureStruct fs = constraint.FeatureStruct.Clone(); fs.ReplaceVariables(varBindings); output.Add(fs, optional); } else { var quantifier = node as Quantifier <Word, ShapeNode>; if (quantifier != null) { for (int i = 0; i < quantifier.MaxOccur; i++) { Untruncate(quantifier, output, i >= quantifier.MinOccur, varBindings); } } else { Untruncate(node, output, optional, varBindings); } } } }
public override bool Add(VariableBindings result) { bool first = true; foreach (Variable var in result.Variables) { if (var.LocalName == null) { continue; } if (!first) { Console.Write(","); } first = false; if (result[var] == null) { continue; } string t = result[var].ToString(); if (result[var] is Literal) { t = ((Literal)result[var]).Value; } Console.Write(t); } Console.WriteLine(); return(true); }
public override bool Add(VariableBindings result) { var nvc = new NameValueCollection(); foreach (string varName in varNames) { Resource resource = result[varName]; if (!string.IsNullOrEmpty(resource.Uri)) { if (string.IsNullOrEmpty(@namespace) || resource.Uri.StartsWith(@namespace)) { nvc[varName] = resource.Uri; } } else if (resource is BNode && !ignoreBnodes) { var bn = resource as BNode; if (string.IsNullOrEmpty(@namespace) || bn.LocalName.StartsWith(@namespace)) { nvc[varName] = bn.LocalName; } } } bindings.Add(nvc); return true; }
//////////////////////////////////////////////////////////////////////////// public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings) { Contract.Requires(oldBindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result <VCExpr>() != null); VariableBindings /*!*/ bindings = oldBindings.Clone(); // bound term variables are replaced with bound term variables // typed in a simpler way List <VCExprVar /*!*/> /*!*/ newBoundVars = BoundVarsAfterErasure(node.BoundVars, bindings); // type variables are replaced with ordinary quantified variables GenBoundVarsForTypeParams(node.TypeParameters, newBoundVars, bindings); VCExpr /*!*/ newNode = HandleQuantifier(node, newBoundVars, bindings); Contract.Assert(newNode != null); if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) { return(newNode); } VariableBindings /*!*/ bindings2; if (!RedoQuantifier(node, (VCExprQuantifier)newNode, node.BoundVars, oldBindings, out bindings2, out newBoundVars)) { return(newNode); } GenBoundVarsForTypeParams(node.TypeParameters, newBoundVars, bindings2); return(HandleQuantifier(node, newBoundVars, bindings2)); }
public Instance(State <TData, TOffset> state, Annotation <TOffset> ann, NullableValue <TOffset>[,] registers, VariableBindings varBindings) { _state = state; _annotation = ann; _registers = registers; _varBindings = varBindings; }
public override void ApplyRhs(Match <Word, ShapeNode> targetMatch, Range <ShapeNode> range, VariableBindings varBindings) { ShapeNode curNode = range.Start; foreach (PatternNode <Word, ShapeNode> node in _rhs.Children.GetNodes(targetMatch.Matcher.Direction)) { if (targetMatch.Input.Shape.Count == 256) { throw new InfiniteLoopException("An epenthesis rewrite rule is stuck in an infinite loop."); } var constraint = (Constraint <Word, ShapeNode>)node; FeatureStruct fs = constraint.FeatureStruct.Clone(); if (varBindings != null) { fs.ReplaceVariables(varBindings); } curNode = targetMatch.Input.Shape.AddAfter(curNode, fs); if (IsIterative) { curNode.SetDirty(true); } } MarkSuccessfulApply(targetMatch.Input); }
public bool Matches(FeatureStruct fs, bool unification, bool useDefaults, VariableBindings varBindings) { if (unification) { return(fs.IsUnifiable(_fs, useDefaults, varBindings) && _negatedFSs.All(nfs => !fs.IsUnifiable(nfs, useDefaults))); } return(_fs.Subsumes(fs, useDefaults, varBindings) && _negatedFSs.All(nfs => !nfs.Subsumes(fs, useDefaults))); }
private void Unapply(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode curNode = span.Start; for (int i = 0; i < _targetCount; i++) { curNode.Annotation.Optional = true; curNode.SetDirty(true); curNode = curNode.Next; } }
public virtual void Clear() { State = null; Output = default(TData); if (_priorities != null) { _priorities.Clear(); } VariableBindings = null; }
public override bool Add(VariableBindings result) { #if !DOTNET2 return(sink.Add(new VariableBindings(vars, result.Values))); #else Resource[] vals = new Resource[result.Values.Count]; result.Values.CopyTo(vals, 0); return(sink.Add(new VariableBindings(vars, vals))); #endif }
public override bool Add(VariableBindings result) { foreach (Variable var in result.Variables) { if (var.LocalName != null && result[var] != null) { Console.WriteLine(var.LocalName + " ==> " + result[var].ToString()); } Console.WriteLine(); } return true; }
internal Match(Matcher <TData, TOffset> matcher, Span <TOffset> span, TData input, IEnumerable <GroupCapture <TOffset> > groupCaptures, IList <string> patternPath, VariableBindings varBindings, Annotation <TOffset> nextAnn) : base(Matcher <TData, TOffset> .EntireMatch, span) { _matcher = matcher; _groupCaptures = new GroupCaptureCollection <TOffset>(span.SpanFactory, groupCaptures); _patternPath = patternPath; _varBindings = varBindings; _input = input; _nextAnn = nextAnn; }
public override bool Add(VariableBindings result) { foreach (Variable variable in result.Variables) { if (variable.LocalName != null && result[variable] != null) { Logger.Debug("?{0} => <{1}>",variable.LocalName, result[variable]); } } return true; }
public override VCExpr VisitNeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result <VCExpr>() != null); // we also have to state that the types are (un)equal, because the // translation does not contain any information about the // relationship between values and types return(Gen.OrSimp(base.VisitNeqOp(node, bindings), Gen.Not(EqualTypes(node[0].Type, node[1].Type, bindings)))); }
internal FstResult(string id, NullableValue <TOffset>[,] registers, TData output, VariableBindings varBindings, int priority, bool isLazy, Annotation <TOffset> nextAnn, int[] priorities) { _id = id; _registers = registers; _output = output; _varBindings = varBindings; _priority = priority; _isLazy = isLazy; _nextAnn = nextAnn; _priorities = priorities; }
public override void ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { foreach (Tuple<ShapeNode, PatternNode<Word, ShapeNode>> tuple in targetMatch.Input.Shape.GetNodes(span).Zip(_rhs.Children)) { var constraints = (Constraint<Word, ShapeNode>) tuple.Item2; tuple.Item1.Annotation.FeatureStruct.PriorityUnion(constraints.FeatureStruct, varBindings); if (IsIterative) tuple.Item1.SetDirty(true); } MarkSuccessfulApply(targetMatch.Input); }
public override bool Add(VariableBindings result) { foreach (Variable var in result.Variables) { if (var.LocalName != null && result[var] != null) { Console.WriteLine(var.LocalName + " ==> " + result[var].ToString()); } } Console.WriteLine(); return(true); }
internal IEnumerable <Match <TData, TOffset> > Matches(TData input, Annotation <TOffset> startAnn, VariableBindings varBindings) { Match <TData, TOffset> match = Match(input, startAnn, varBindings); while (match.Success) { yield return(match); match = match.NextMatch(varBindings); } }
public override bool Add(VariableBindings result) { StringBuilder output = new StringBuilder(); foreach (Variable var in result.Variables) { output.Append("?" + var.LocalName + " = "); output.Append(result[var]); output.Append(" , "); } Console.WriteLine(output.ToString()); return(true); }
public override bool Add(VariableBindings result) { output.WriteLine("<tr>"); foreach (Variable var in result.Variables) { if (var.LocalName == null) continue; Resource varTarget = result[var]; string t = varTarget.ToString(); if (varTarget is Literal) t = ((Literal)varTarget).Value; output.WriteLine("<td>" + t + "</td>"); } output.WriteLine("</tr>"); return true; }
internal FstResult(IEqualityComparer <Register <TOffset> [, ]> registersEqualityComparer, string id, Register <TOffset>[,] registers, TData output, VariableBindings varBindings, int priority, bool isLazy, Annotation <TOffset> nextAnn, int[] priorities, int order) { _registersEqualityComparer = registersEqualityComparer; _id = id; _registers = registers; _output = output; _varBindings = varBindings; _priority = priority; _isLazy = isLazy; _nextAnn = nextAnn; _priorities = priorities; _order = order; }
public override bool Add(VariableBindings result) { bool first = true; foreach (Variable var in result.Variables) { if (var.LocalName == null) continue; if (!first) Console.Write(","); first = false; if (result[var] == null) continue; string t = result[var].ToString(); if (result[var] is Literal) t = ((Literal)result[var]).Value; Console.Write(t); } Console.WriteLine(); return true; }
public override bool Add(VariableBindings result) { Resource subj = si == -1 ? d.Subject : result.Values[si]; Resource pred = pi == -1 ? d.Predicate : result.Values[pi]; Resource obj = oi == -1 ? d.Object : result.Values[oi]; if (!(subj is Entity) || !(pred is Entity)) { return(true); } if (litFilters != null && !LiteralFilter.MatchesFilters(obj, litFilters, null)) { return(true); } return(sink.Add(new Statement((Entity)subj, (Entity)pred, obj))); }
public override void ApplyRhs(Match <Word, ShapeNode> targetMatch, Range <ShapeNode> range, VariableBindings varBindings) { foreach (Tuple <ShapeNode, PatternNode <Word, ShapeNode> > tuple in targetMatch.Input.Shape.GetNodes(range) .Zip(_rhs.Children)) { var constraints = (Constraint <Word, ShapeNode>)tuple.Item2; tuple.Item1.Annotation.FeatureStruct.PriorityUnion(constraints.FeatureStruct, varBindings); if (IsIterative) { tuple.Item1.SetDirty(true); } } MarkSuccessfulApply(targetMatch.Input); }
public override void ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode curNode = span.Start; foreach (PatternNode<Word, ShapeNode> node in _rhs.Children.GetNodes(targetMatch.Matcher.Direction)) { if (targetMatch.Input.Shape.Count == 256) throw new InfiniteLoopException("An epenthesis rewrite rule is stuck in an infinite loop."); var constraint = (Constraint<Word, ShapeNode>) node; FeatureStruct fs = constraint.FeatureStruct.DeepClone(); if (varBindings != null) fs.ReplaceVariables(varBindings); curNode = targetMatch.Input.Shape.AddAfter(curNode, fs); if (IsIterative) curNode.SetDirty(true); } MarkSuccessfulApply(targetMatch.Input); }
public VCExpr BestTypeVarExtractor( TypeVariable typeVar, VCExprVar dummyVariable, List <Type> vcFunctionValueTypes, List <VCExprVar> vcFunctionValueArgs) { var varBindings = new Dictionary <VCExprVar, VCExprVar>(); var typeVarBindings = new Dictionary <TypeVariable, VCExpr>(); typeVarBindings.Add(typeVar, dummyVariable); var b = new VariableBindings(varBindings, typeVarBindings); var binding = AxiomBuilder.BestTypeVarExtractors(new List <TypeVariable> { typeVar }, vcFunctionValueTypes, vcFunctionValueArgs, b); return(binding[0].E); }
private VCExpr EqualTypes(Type t0, Type t1, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(t1 != null); Contract.Requires(t0 != null); Contract.Ensures(Contract.Result <VCExpr>() != null); if (t0.Equals(t1)) { return(VCExpressionGenerator.True); } VCExpr /*!*/ t0Expr = AxBuilder.Type2Term(t0, bindings.TypeVariableBindings); Contract.Assert(t0Expr != null); VCExpr /*!*/ t1Expr = AxBuilder.Type2Term(t1, bindings.TypeVariableBindings); Contract.Assert(t1Expr != null); return(Gen.Eq(t0Expr, t1Expr)); }
private IEnumerable <Match <TData, TOffset> > AllMatches(TData input, Annotation <TOffset> startAnn, VariableBindings varBindings) { IEnumerable <FstResult <TData, TOffset> > results; if (_fsa.Transduce(input, startAnn, varBindings, _settings.AnchoredToStart, _settings.AnchoredToEnd, _settings.UseDefaults, out results)) { IEnumerable <Match <TData, TOffset> > matches = results.Select(fm => CreatePatternMatch(input, fm)); if (!_fsa.IsDeterministic && !_settings.AllSubmatches) { return(matches.GroupBy(m => m, _matchComparer).Select(group => group.First())); } return(matches); } return(Enumerable.Empty <Match <TData, TOffset> >()); }
protected TraversalMethodBase(Fst <TData, TOffset> fst, TData data, VariableBindings varBindings, bool startAnchor, bool endAnchor, bool useDefaults) { _fst = fst; _data = data; _varBindings = varBindings; _startAnchor = startAnchor; _endAnchor = endAnchor; _useDefaults = useDefaults; _annotations = new List <Annotation <TOffset> >(); // insertion sort foreach (Annotation <TOffset> topAnn in _data.Annotations.GetNodes(_fst.Direction)) { foreach (Annotation <TOffset> ann in topAnn.GetNodesDepthFirst(_fst.Direction)) { if (!_fst.Filter(ann)) { continue; } int i = _annotations.Count - 1; while (i >= 0 && CompareAnnotations(_annotations[i], ann) > 0) { if (i + 1 == _annotations.Count) { _annotations.Add(_annotations[i]); } else { _annotations[i + 1] = _annotations[i]; } i--; } if (i + 1 == _annotations.Count) { _annotations.Add(ann); } else { _annotations[i + 1] = ann; } } } _cachedInstances = new Queue <TInst>(); }
private void CheckAccepting(int annIndex, Register <TOffset>[,] registers, TData output, VariableBindings varBindings, Arc <TData, TOffset> arc, ICollection <FstResult <TData, TOffset> > curResults, IList <int> priorities) { if (arc.Target.IsAccepting && (!_endAnchor || annIndex == _annotations.Count)) { Annotation <TOffset> ann = annIndex < _annotations.Count ? _annotations[annIndex] : _data.Annotations.GetEnd(_fst.Direction); var matchRegisters = (Register <TOffset> [, ])registers.Clone(); ExecuteCommands(matchRegisters, arc.Target.Finishers, new Register <TOffset>(), new Register <TOffset>()); if (arc.Target.AcceptInfos.Count > 0) { foreach (AcceptInfo <TData, TOffset> acceptInfo in arc.Target.AcceptInfos) { TData resOutput = output; var cloneable = resOutput as IDeepCloneable <TData>; if (cloneable != null) { resOutput = cloneable.DeepClone(); } var candidate = new FstResult <TData, TOffset>(_fst.RegistersEqualityComparer, acceptInfo.ID, matchRegisters, resOutput, varBindings == null ? null : varBindings.DeepClone(), acceptInfo.Priority, arc.Target.IsLazy, ann, priorities == null ? null : priorities.ToArray(), curResults.Count); if (acceptInfo.Acceptable == null || acceptInfo.Acceptable(_data, candidate)) { curResults.Add(candidate); } } } else { TData resOutput = output; var cloneable = resOutput as IDeepCloneable <TData>; if (cloneable != null) { resOutput = cloneable.DeepClone(); } curResults.Add(new FstResult <TData, TOffset>(_fst.RegistersEqualityComparer, null, matchRegisters, resOutput, varBindings == null ? null : varBindings.DeepClone(), -1, arc.Target.IsLazy, ann, priorities == null ? null : priorities.ToArray(), curResults.Count)); } } }
private void Unapply(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode curNode = IsTargetEmpty ? span.Start : span.End; foreach (Constraint<Word, ShapeNode> constraint in _analysisRhs.Children.Cast<Constraint<Word, ShapeNode>>()) { FeatureStruct fs = constraint.FeatureStruct.DeepClone(); if (varBindings != null) { fs.ReplaceVariables(varBindings); fs.RemoveVariables(); } curNode = targetMatch.Input.Shape.AddAfter(curNode, fs, true); } for (int i = 0; i < _targetCount; i++) { curNode.Annotation.Optional = true; curNode = curNode.Next; } }
public override bool Add(VariableBindings result) { output.WriteLine("<tr>"); foreach (Variable var in result.Variables) { if (var.LocalName == null) { continue; } Resource varTarget = result[var]; string t = varTarget.ToString(); if (varTarget is Literal) { t = ((Literal)varTarget).Value; } output.WriteLine("<td>" + t + "</td>"); } output.WriteLine("</tr>"); return(true); }
public override void ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings) { ShapeNode curNode = span.End; foreach (PatternNode<Word, ShapeNode> node in _rhs.Children) { var constraint = (Constraint<Word, ShapeNode>) node; FeatureStruct fs = constraint.FeatureStruct.DeepClone(); if (varBindings != null) fs.ReplaceVariables(varBindings); curNode = targetMatch.Input.Shape.AddAfter(curNode, fs); if (IsIterative) curNode.SetDirty(true); } ShapeNode[] nodes = targetMatch.Input.Shape.GetNodes(span).ToArray(); for (int i = 0; i < _targetCount; i++) nodes[i].SetDeleted(true); MarkSuccessfulApply(targetMatch.Input); }
/// <summary> /// Assigns the instance URI from the SPARQL result bindings. /// </summary> /// <param name="obj">The object to assign the URI to.</param> /// <param name="queryAlias">The query alias that was used in LINQ and SPARQL.</param> /// <param name="semwebResult">The semweb result to take the value from.</param> private void AssignInstanceUri(OwlInstanceSupertype obj, string queryAlias, VariableBindings semwebResult) { // if there is no alias, then there's no way to work out what contains the instance URI if (string.IsNullOrEmpty(queryAlias)) { return; } // if there is a binding with the same name as the alias if (semwebResult.Variables.Map(v => v.LocalName).Contains(queryAlias)) { // get string representation of the instance URI string uri = semwebResult[queryAlias].ToString(); // is it enclosed in angle brackets? then strip them. if (uri.StartsWith("<") && uri.EndsWith(">")) { uri = uri.Substring(1, uri.Length - 2); } // can this be parsed as a URI? if so then assign to instance URI property of obj if (Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute)) { obj.InstanceUri = uri; } } }
public override bool Add(VariableBindings result) { //dt.Columns.Add("Disease"); //dt.Columns.Add("Symptoms"); string nam = string.Empty; string med = string.Empty; string symp = string.Empty; foreach (Variable var in result.Variables) { if (var.LocalName != null && result[var] != null) { if (var.LocalName == "medi") med = result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#", "").Replace(">", ""); if (var.LocalName == "symp") symp = result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#", "").Replace(">", ""); if (var.LocalName == "dis") nam = result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#", "").Replace(">", ""); } Console.WriteLine(); } list.Add(new Result(nam, symp, med, _pName)); return true; }
public abstract void ApplyRhs(Match<Word, ShapeNode> targetMatch, Span<ShapeNode> span, VariableBindings varBindings);
/// <summary> /// Extracts the corresponding value from the SemWeb results for a member access projection. /// </summary> /// <param name="vb">The SemWeb results.</param> /// <returns>the value that was extracted (and converted) from the results.</returns> private object ExtractMemberAccess(VariableBindings vb) { // work out if the SelectExpression really is a member access var ue = (SelectExpression).Arguments[1] as UnaryExpression; if (ue == null) throw new ArgumentException("incompatible expression type"); var le = ue.Operand as LambdaExpression; if (le == null) throw new ApplicationException("Incompatible expression type found when building ontology projection"); if (le.Body is MemberExpression) { // work out which member is being queried on var memberExpression = (MemberExpression) le.Body; MemberInfo memberInfo = memberExpression.Member; // get its name and use that as a key into the results string vVal = vb[memberInfo.Name].ToString(); // convert the result from XSDT format to .NET types var tc = new XsdtTypeConverter(); return tc.Parse(vVal); } return null; }
/*!*/ public override VCExpr VisitSelectOp(VCExprNAry/*!*/ node, VariableBindings/*!*/ bindings) { Contract.Requires(node != null); Contract.Requires(bindings != null); Contract.Ensures(Contract.Result<VCExpr>() != null); MapType/*!*/ mapType = node[0].Type.AsMap; Contract.Assert(mapType != null); List<Type>/*!*/ instantiations; // not used Function/*!*/ select = AxBuilder.MapTypeAbstracter.Select(mapType, out instantiations); Contract.Assert(select != null); List<int>/*!*/ explicitTypeParams = AxBuilderPremisses.MapTypeAbstracterPremisses .ExplicitSelectTypeParams(mapType); Contract.Assert(select.InParams.Count == explicitTypeParams.Count + node.Arity); List<Type/*!*/>/*!*/ typeArgs = new List<Type/*!*/>(explicitTypeParams.Count); foreach (int i in explicitTypeParams) typeArgs.Add(node.TypeArguments[i]); return HandleFunctionOp(select, typeArgs, node, bindings); }
public override bool Add(VariableBindings result) { //dt.Columns.Add("Disease"); //dt.Columns.Add("Symptoms"); foreach (Variable var in result.Variables) { if (var.LocalName != null && result[var] != null) { //if (var.LocalName == "name") al.Add(result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#", "").Replace(">", "")); //if(var.LocalName=="symp") // row[1]=(result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#","")).Replace(">",""); // dt.Rows.Add((result[var].ToString().Replace("<http://www.owl-ontologies.com/Ontology1183162121.owl#","")).Replace(">","")); } Console.WriteLine(); } return true; }
//////////////////////////////////////////////////////////////////////////// public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings) { Contract.Requires(oldBindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result<VCExpr>() != null); VariableBindings bindings = oldBindings.Clone(); // determine the bound vars that actually occur in the body or // in any of the triggers (if some variables do not occur, we // need to take special care of type parameters that only occur // in the types of such variables) FreeVariableCollector coll = new FreeVariableCollector(); coll.Collect(node.Body); foreach (VCTrigger trigger in node.Triggers) { if (trigger.Pos) foreach (VCExpr/*!*/ e in trigger.Exprs) { Contract.Assert(e != null); coll.Collect(e); } } List<VCExprVar/*!*/> occurringVars = new List<VCExprVar/*!*/>(node.BoundVars.Count); foreach (VCExprVar var in node.BoundVars) if (coll.FreeTermVars.ContainsKey(var)) occurringVars.Add(var); occurringVars.TrimExcess(); // bound term variables are replaced with bound term variables typed in // a simpler way List<VCExprVar/*!*/>/*!*/ newBoundVars = BoundVarsAfterErasure(occurringVars, bindings); Contract.Assert(cce.NonNullElements(newBoundVars)); VCExpr/*!*/ newNode = HandleQuantifier(node, occurringVars, newBoundVars, bindings); Contract.Assert(newNode != null); if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) return newNode; VariableBindings bindings2; if (!RedoQuantifier(node, (VCExprQuantifier)newNode, occurringVars, oldBindings, out bindings2, out newBoundVars)) return newNode; return HandleQuantifier(node, occurringVars, newBoundVars, bindings2); }
/*!*/ internal VCExpr GenFunctionAxiom(Function/*!*/ fun, List<TypeVariable/*!*/>/*!*/ implicitTypeParams, List<TypeVariable/*!*/>/*!*/ explicitTypeParams, List<Type/*!*/>/*!*/ originalInTypes, Type/*!*/ originalResultType) { Contract.Requires(cce.NonNullElements(implicitTypeParams)); Contract.Requires(fun != null); Contract.Requires(cce.NonNullElements(explicitTypeParams)); Contract.Requires(cce.NonNullElements(originalInTypes)); Contract.Requires(originalResultType != null); Contract.Requires(originalInTypes.Count + explicitTypeParams.Count == fun.InParams.Count); Contract.Ensures(Contract.Result<VCExpr>() != null); if (CommandLineOptions.Clo.TypeEncodingMethod == CommandLineOptions.TypeEncoding.None) { return VCExpressionGenerator.True; } List<VCExprVar/*!*/>/*!*/ typedInputVars = new List<VCExprVar/*!*/>(originalInTypes.Count); int i = 0; foreach (Type/*!*/ t in originalInTypes) { Contract.Assert(t != null); typedInputVars.Add(Gen.Variable("arg" + i, t)); i = i + 1; } VariableBindings/*!*/ bindings = new VariableBindings(); // type parameters that have to be given explicitly are replaced // with universally quantified type variables List<VCExprVar/*!*/>/*!*/ boundVars = new List<VCExprVar/*!*/>(explicitTypeParams.Count + typedInputVars.Count); foreach (TypeVariable/*!*/ var in explicitTypeParams) { Contract.Assert(var != null); VCExprVar/*!*/ newVar = Gen.Variable(var.Name, T); boundVars.Add(newVar); bindings.TypeVariableBindings.Add(var, newVar); } // bound term variables are replaced with bound term variables typed in // a simpler way foreach (VCExprVar/*!*/ var in typedInputVars) { Contract.Assert(var != null); Type/*!*/ newType = TypeAfterErasure(var.Type); Contract.Assert(newType != null); VCExprVar/*!*/ newVar = Gen.Variable(var.Name, newType); Contract.Assert(newVar != null); boundVars.Add(newVar); bindings.VCExprVarBindings.Add(var, newVar); } List<VCExprLetBinding/*!*/> typeVarBindings = GenTypeParamBindings(implicitTypeParams, typedInputVars, bindings, true); Contract.Assert(cce.NonNullElements(typeVarBindings)); VCExpr/*!*/ funApp = Gen.Function(fun, HelperFuns.ToVCExprList(boundVars)); Contract.Assert(funApp != null); VCExpr/*!*/ conclusion = Gen.Eq(TypeOf(funApp), Type2Term(originalResultType, bindings.TypeVariableBindings)); Contract.Assert(conclusion != null); VCExpr conclusionWithPremisses = // leave out antecedents of function type axioms ... they don't appear necessary, // because a function can always be extended to all U-values (right?) // AddTypePremisses(typeVarBindings, typePremisses, true, conclusion); Gen.Let(typeVarBindings, conclusion); if (boundVars.Count > 0) { List<VCTrigger/*!*/> triggers = HelperFuns.ToList(Gen.Trigger(true, HelperFuns.ToList(funApp))); Contract.Assert(cce.NonNullElements(triggers)); return Gen.Forall(boundVars, triggers, "funType:" + fun.Name, -1, conclusionWithPremisses); } else { return conclusionWithPremisses; } }
/// <summary> /// stores the result from a SemWeb result into a <see cref="PropertyInfo"/> doing whatever conversions are required. /// </summary> /// <param name="semwebBindings">The incoming result from semweb.</param> /// <param name="obj">The object instance on wqhich the property is to be set</param> /// <param name="propertyInfo">The <see cref="PropertyInfo"/> identifying the property to be populated with the value stored in <see cref="semwebBindings"/>.</param> public static void PopulateProperty(VariableBindings semwebBindings, object obj, PropertyInfo propertyInfo) { if (semwebBindings[propertyInfo.Name] != null) { string vVal = semwebBindings[propertyInfo.Name].ToString(); var tc = new XsdtTypeConverter(); object x = tc.Parse(vVal); // vVal = RemoveEnclosingQuotesOnString(vVal, pi); // if (IsXsdtEncoded(vVal)) // vVal = DecodeXsdtString(vVal); if (x is IConvertible) propertyInfo.SetValue(obj, Convert.ChangeType(x, propertyInfo.PropertyType), null); else // if it's not convertible, it could be because the type is an MS XSDT type rather than a .NET primitive if (x.GetType().Namespace == "System.Runtime.Remoting.Metadata.W3cXsd2001") { switch (x.GetType().Name) { case "SoapDate": var d = (SoapDate) x; propertyInfo.SetValue(obj, Convert.ChangeType(d.Value, propertyInfo.PropertyType), null); break; default: break; } } else if (propertyInfo.PropertyType == typeof (string)) { propertyInfo.SetValue(obj, x.ToString(), null); } } }
/////////////////////////////////////////////////////////////////////////// // Extract the instantiations of type variables from the concrete types of // term variables. E.g., for a function f<a>(x : C a), we would extract the // instantiation of "a" by looking at the concrete type of "x". /*!*/ public List<VCExprLetBinding/*!*/> BestTypeVarExtractors(List<TypeVariable/*!*/>/*!*/ vars, List<Type/*!*/>/*!*/ types, List<VCExprVar/*!*/>/*!*/ concreteTypeSources, VariableBindings/*!*/ bindings) { Contract.Requires(cce.NonNullElements(vars)); Contract.Requires(cce.NonNullElements(types)); Contract.Requires(cce.NonNullElements(concreteTypeSources)); Contract.Requires(bindings != null); Contract.Ensures(cce.NonNullElements(Contract.Result<List<VCExprLetBinding>>())); List<VCExprLetBinding/*!*/>/*!*/ typeParamBindings = new List<VCExprLetBinding/*!*/>(); foreach (TypeVariable/*!*/ var in vars) { Contract.Assert(var != null); VCExpr extractor = BestTypeVarExtractor(var, types, concreteTypeSources); if (extractor != null) typeParamBindings.Add( Gen.LetBinding((VCExprVar)bindings.TypeVariableBindings[var], extractor)); } return typeParamBindings; }
private VCExpr HandleFunctionOp(Function newFun, List<Type/*!*/>/*!*/ typeArgs/*!*/, IEnumerable<VCExpr/*!*/>/*!*/ oldArgs, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(newFun != null); Contract.Requires(cce.NonNullElements(typeArgs/*!*/)); Contract.Requires(cce.NonNullElements(oldArgs)); Contract.Ensures(Contract.Result<VCExpr>() != null); // UGLY: the code for tracking polarities should be factored out int oldPolarity = Eraser.Polarity; Eraser.Polarity = 0; List<VCExpr/*!*/>/*!*/ newArgs = new List<VCExpr/*!*/>(typeArgs.Count); // translate the explicit type arguments foreach (Type/*!*/ t in typeArgs) { Contract.Assert(t != null); newArgs.Add(AxBuilder.Type2Term(t, bindings.TypeVariableBindings)); } // recursively translate the value arguments foreach (VCExpr/*!*/ arg in oldArgs) { Contract.Assert(arg != null); Type/*!*/ newType = cce.NonNull(newFun.InParams[newArgs.Count]).TypedIdent.Type; newArgs.Add(AxBuilder.Cast(Eraser.Mutate(arg, bindings), newType)); } Eraser.Polarity = oldPolarity; return Gen.Function(newFun, newArgs); }
public override VCExpr VisitStoreOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result<VCExpr>() != null); List<Type>/*!*/ instantiations; // not used Function/*!*/ store = AxBuilder.MapTypeAbstracter.Store(node[0].Type.AsMap, out instantiations); Contract.Assert(store != null); return HandleFunctionOp(store, // the store function never has explicit // type parameters new List<Type/*!*/>(), node, bindings); }
private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, List<TypeVariable/*!*/>/*!*/ explicitSelectParams) { Contract.Requires(mapResult != null); Contract.Requires(store != null); Contract.Requires(select != null); Contract.Requires(cce.NonNullElements(explicitSelectParams)); Contract.Ensures(Contract.Result<VCExpr>() != null); int arity = store.InParams.Count - 2; List<Type/*!*/> indexTypes = new List<Type/*!*/>(); for (int i = 1; i < store.InParams.Count - 1; i++) { indexTypes.Add(cce.NonNull(store.InParams[i]).TypedIdent.Type); } Contract.Assert(indexTypes.Count == arity); List<VCExprVar/*!*/>/*!*/ indexes0 = HelperFuns.VarVector("x", indexTypes, Gen); Contract.Assert(cce.NonNullElements(indexes0)); List<VCExprVar/*!*/>/*!*/ indexes1 = HelperFuns.VarVector("y", indexTypes, Gen); Contract.Assert(cce.NonNullElements(indexes1)); VCExprVar/*!*/ m = Gen.Variable("m", AxBuilder.U); Contract.Assert(m != null); VCExprVar/*!*/ val = Gen.Variable("val", cce.NonNull(select.OutParams[0]).TypedIdent.Type); Contract.Assert(val != null); // extract the explicit type parameters from the actual result type ... VCExprVar/*!*/ typedVal = Gen.Variable("val", mapResult); Contract.Assert(typedVal != null); VariableBindings/*!*/ bindings = new VariableBindings(); bindings.VCExprVarBindings.Add(typedVal, val); List<VCExprLetBinding/*!*/>/*!*/ letBindings = AxBuilderPremisses.GenTypeParamBindings(explicitSelectParams, HelperFuns.ToList(typedVal), bindings, true); Contract.Assert(cce.NonNullElements(letBindings)); // ... and quantify the introduced term variables for type // parameters universally List<VCExprVar/*!*/>/*!*/ typeParams = new List<VCExprVar/*!*/>(explicitSelectParams.Count); List<VCExpr/*!*/>/*!*/ typeParamsExpr = new List<VCExpr/*!*/>(explicitSelectParams.Count); foreach (TypeVariable/*!*/ var in explicitSelectParams) { Contract.Assert(var != null); VCExprVar/*!*/ newVar = (VCExprVar)bindings.TypeVariableBindings[var]; Contract.Assert(newVar != null); typeParams.Add(newVar); typeParamsExpr.Add(newVar); } VCExpr/*!*/ storeExpr = Store(store, m, indexes0, val); Contract.Assert(storeExpr != null); VCExpr/*!*/ selectWithoutStoreExpr = Select(select, typeParamsExpr, m, indexes1); Contract.Assert(selectWithoutStoreExpr != null); VCExpr/*!*/ selectExpr = Select(select, typeParamsExpr, storeExpr, indexes1); Contract.Assert(selectExpr != null); VCExpr/*!*/ selectEq = Gen.Eq(selectExpr, selectWithoutStoreExpr); Contract.Assert(selectEq != null); List<VCExprVar/*!*/>/*!*/ quantifiedVars = new List<VCExprVar/*!*/>(indexes0.Count + indexes1.Count + 2); quantifiedVars.Add(val); quantifiedVars.Add(m); quantifiedVars.AddRange(indexes0); quantifiedVars.AddRange(indexes1); quantifiedVars.AddRange(typeParams); List<VCTrigger/*!*/>/*!*/ triggers = new List<VCTrigger/*!*/>(); Contract.Assert(cce.NonNullElements(triggers)); VCExpr/*!*/ axiom = VCExpressionGenerator.True; Contract.Assert(axiom != null); // first non-interference criterium: the queried location is // different from the assigned location for (int i = 0; i < arity; ++i) { VCExpr/*!*/ indexesEq = Gen.Eq(indexes0[i], indexes1[i]); VCExpr/*!*/ matrix = Gen.Or(indexesEq, selectEq); VCExpr/*!*/ conjunct = Gen.Forall(quantifiedVars, triggers, "mapAx1:" + select.Name + ":" + i, 0, matrix); Contract.Assert(indexesEq != null); Contract.Assert(matrix != null); Contract.Assert(conjunct != null); axiom = Gen.AndSimp(axiom, conjunct); } // second non-interference criterion: the queried type is // different from the assigned type VCExpr/*!*/ typesEq = VCExpressionGenerator.True; foreach (VCExprLetBinding/*!*/ b in letBindings) { Contract.Assert(b != null); typesEq = Gen.AndSimp(typesEq, Gen.Eq(b.V, b.E)); } VCExpr/*!*/ matrix2 = Gen.Or(typesEq, selectEq); VCExpr/*!*/ conjunct2 = Gen.Forall(quantifiedVars, triggers, "mapAx2:" + select.Name, 0, matrix2); axiom = Gen.AndSimp(axiom, conjunct2); return axiom; }
private VCExpr HandleQuantifier(VCExprQuantifier node, List<VCExprVar/*!*/>/*!*/ occurringVars/*!*/, List<VCExprVar/*!*/>/*!*/ newBoundVars, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Requires(cce.NonNullElements(occurringVars/*!*/)); Contract.Requires(cce.NonNullElements(newBoundVars)); Contract.Ensures(Contract.Result<VCExpr>() != null); List<VCExprLetBinding/*!*/>/*!*/ typeVarBindings = AxBuilderPremisses.GenTypeParamBindings(node.TypeParameters, occurringVars, bindings, true); Contract.Assert(typeVarBindings != null); // Check whether some of the type parameters could not be // determined from the bound variable types. In this case, we // quantify explicitly over these variables if (typeVarBindings.Count < node.TypeParameters.Count) { foreach (TypeVariable/*!*/ var in node.TypeParameters) { Contract.Assert(var != null); if (typeVarBindings.All(b => !b.V.Equals(var))) newBoundVars.Add((VCExprVar)bindings.TypeVariableBindings[var]); } } // the lists of old and new bound variables for which type // antecedents are to be generated List<VCExprVar/*!*/>/*!*/ varsWithTypeSpecs = new List<VCExprVar/*!*/>(); List<VCExprVar/*!*/>/*!*/ newVarsWithTypeSpecs = new List<VCExprVar/*!*/>(); if (!IsUniversalQuantifier(node) || CommandLineOptions.Clo.TypeEncodingMethod == CommandLineOptions.TypeEncoding.Predicates) { foreach (VCExprVar/*!*/ oldVar in occurringVars) { Contract.Assert(oldVar != null); varsWithTypeSpecs.Add(oldVar); newVarsWithTypeSpecs.Add(bindings.VCExprVarBindings[oldVar]); } } // else, no type antecedents are created for any variables List<VCTrigger/*!*/>/*!*/ furtherTriggers; VCExpr/*!*/ typePremisses = GenTypePremisses(varsWithTypeSpecs, newVarsWithTypeSpecs, bindings.TypeVariableBindings, typeVarBindings, out furtherTriggers); Contract.Assert(cce.NonNullElements(furtherTriggers)); Contract.Assert(typePremisses != null); List<VCTrigger/*!*/>/*!*/ newTriggers = MutateTriggers(node.Triggers, bindings); Contract.Assert(cce.NonNullElements(newTriggers)); newTriggers.AddRange(furtherTriggers); newTriggers = AddLets2Triggers(newTriggers, typeVarBindings); VCExpr/*!*/ newBody = Mutate(node.Body, bindings); Contract.Assert(newBody != null); // assemble the new quantified formula if (CommandLineOptions.Clo.TypeEncodingMethod == CommandLineOptions.TypeEncoding.None) { typePremisses = VCExpressionGenerator.True; } VCExpr/*!*/ bodyWithPremisses = AxBuilderPremisses.AddTypePremisses(typeVarBindings, typePremisses, node.Quan == Quantifier.ALL, AxBuilder.Cast(newBody, Type.Bool)); Contract.Assert(bodyWithPremisses != null); if (newBoundVars.Count == 0) // might happen that no bound variables are left return bodyWithPremisses; foreach (VCExprVar/*!*/ v in newBoundVars) { Contract.Assert(v != null); if (v.Type == AxBuilderPremisses.U) { newTriggers.Add(Gen.Trigger(false, AxBuilderPremisses.Cast(v, Type.Int))); newTriggers.Add(Gen.Trigger(false, AxBuilderPremisses.Cast(v, Type.Bool))); } } return Gen.Quantify(node.Quan, new List<TypeVariable/*!*/>(), newBoundVars, newTriggers, node.Infos, bodyWithPremisses); }
/// <summary> /// A callback interface that gets called by SemWeb when results are sent /// back from a remote SPAZRQL source. This gets each unique set of bindings /// in turn. It can either store the results or deserialise them on the spot. /// </summary> /// <returns>true if the deserialiser was able to use the result or false otherwise</returns> public override bool Add(VariableBindings result) { #region Tracing #line hidden if (Logger.IsDebugEnabled) { Logger.Debug("Got Result {0}.", result.ToString()); } #line default #endregion if (IsSelectMember(SelectExpression)) { IncomingResults.Add(ExtractMemberAccess(result)); return true; } if (originalType == null) throw new ApplicationException("need ontology type to create"); object t; IEnumerable<MemberInfo> props = GetPropertiesToPopulate(originalType, instanceType); if (originalType == instanceType) { #region not using a projection t = Activator.CreateInstance(instanceType); #region Tracing #line hidden if (Logger.IsDebugEnabled) { Logger.Debug("created new instance of {0}.", t.GetType().Name); } #line default #endregion AssignDataContext(t as OwlInstanceSupertype, DataContext); AssignInstanceUri(t as OwlInstanceSupertype, InstanceName, result); foreach (PropertyInfo pi in props) { if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition().Name.StartsWith("Entity")) continue; try { PopulateProperty(result, t, pi); } catch (ArgumentException ae) { #region Tracing #line hidden if (Logger.IsErrorEnabled) { Logger.ErrorEx("Unable to populate property " + pi.Name, ae); Logger.Error("continuing"); } #line default #endregion } catch (Exception e) { #region Tracing #line hidden if (Logger.IsErrorEnabled) { Logger.ErrorEx("Unable to populate property " + pi.Name, e); } #line default #endregion return false; } } #endregion } else { #region using a projection var args = new List<object>(); foreach (PropertyInfo pi in props) { try { if (result[pi.Name] != null) { string vVal = result[pi.Name].ToString(); vVal = RemoveEnclosingQuotesOnString(vVal, pi); if (IsXsdtEncoded(vVal)) vVal = DecodeXsdtString(vVal); args.Add(Convert.ChangeType(vVal, pi.PropertyType)); } } catch (Exception e) { Console.WriteLine(e); return false; } } t = Activator.CreateInstance(instanceType, args.ToArray()); #endregion } if (Distinct) { if (ObjectIsUniqueSoFar(t as OwlInstanceSupertype)) IncomingResults.Add(t); } else IncomingResults.Add(t); return true; }
public override VCExpr VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result<VCExpr>() != null); Function/*!*/ oriFun = ((VCExprBoogieFunctionOp)node.Op).Func; Contract.Assert(oriFun != null); UntypedFunction untypedFun = AxBuilderPremisses.Typed2Untyped(oriFun); Contract.Assert(untypedFun.Fun.InParams.Count == untypedFun.ExplicitTypeParams.Count + node.Arity); List<Type/*!*/>/*!*/ typeArgs = ExtractTypeArgs(node, oriFun.TypeParameters, untypedFun.ExplicitTypeParams); return HandleFunctionOp(untypedFun.Fun, typeArgs, node, bindings); }
/////////////////////////////////////////////////////////////////////////// // Generate type premisses and type parameter bindings for quantifiers, functions, procedures // let-bindings to extract the instantiations of type parameters /*!*/ public List<VCExprLetBinding/*!*/> GenTypeParamBindings(// the original bound variables and (implicit) type parameters List<TypeVariable/*!*/>/*!*/ typeParams, List<VCExprVar/*!*/>/*!*/ oldBoundVars, // VariableBindings to which the translation // TypeVariable -> VCExprVar is added VariableBindings/*!*/ bindings, bool addTypeVarsToBindings) { Contract.Requires(typeParams != null); Contract.Requires(cce.NonNullElements(oldBoundVars)); Contract.Requires(bindings != null); Contract.Ensures(cce.NonNullElements(Contract.Result<List<VCExprLetBinding>>())); // type variables are replaced with ordinary variables that are bound using a // let-expression if (addTypeVarsToBindings) { foreach (TypeVariable/*!*/ tvar in typeParams) { Contract.Assert(tvar != null); bindings.TypeVariableBindings.Add(tvar, Gen.Variable(tvar.Name, T)); } } // extract the values of type variables from the term variables List<VCExprVar/*!*/>/*!*/ UtypedVars = new List<VCExprVar/*!*/>(oldBoundVars.Count); List<Type/*!*/>/*!*/ originalTypes = new List<Type/*!*/>(oldBoundVars.Count); foreach (VCExprVar var in oldBoundVars) { VCExprVar/*!*/ newVar = bindings.VCExprVarBindings[var]; if (newVar.Type.Equals(U)) { UtypedVars.Add(newVar); originalTypes.Add(var.Type); } } UtypedVars.TrimExcess(); originalTypes.TrimExcess(); return BestTypeVarExtractors(typeParams, originalTypes, UtypedVars, bindings); }
/// <summary> /// Generate: /// (forall m, indexes, val :: /// type(val) == T ==> /// select(store(m, indexes, val), indexes) == val) /// where the quantifier body is also enclosed in a let that defines portions of T, if needed. /// </summary> private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, List<TypeVariable/*!*/>/*!*/ implicitTypeParamsSelect, List<TypeVariable/*!*/>/*!*/ explicitTypeParamsSelect, List<Type/*!*/>/*!*/ originalInTypes) { Contract.Requires(mapResult != null); Contract.Requires(store != null); Contract.Requires(select != null); Contract.Requires(cce.NonNullElements(implicitTypeParamsSelect)); Contract.Requires(cce.NonNullElements(originalInTypes)); Contract.Requires(cce.NonNullElements(explicitTypeParamsSelect)); Contract.Ensures(Contract.Result<VCExpr>() != null); int arity = store.InParams.Count - 2; List<VCExprVar/*!*/> inParams = new List<VCExprVar/*!*/>(); List<VCExprVar/*!*/> quantifiedVars = new List<VCExprVar/*!*/>(store.InParams.Count); VariableBindings bindings = new VariableBindings(); // bound variable: m VCExprVar typedM = Gen.Variable("m", originalInTypes[0]); VCExprVar m = Gen.Variable("m", AxBuilder.U); inParams.Add(typedM); quantifiedVars.Add(m); bindings.VCExprVarBindings.Add(typedM, m); // bound variables: indexes List<Type/*!*/> origIndexTypes = new List<Type/*!*/>(arity); List<Type/*!*/> indexTypes = new List<Type/*!*/>(arity); for (int i = 1; i < store.InParams.Count - 1; i++) { origIndexTypes.Add(originalInTypes[i]); indexTypes.Add(cce.NonNull(store.InParams[i]).TypedIdent.Type); } Contract.Assert(arity == indexTypes.Count); List<VCExprVar/*!*/> typedArgs = HelperFuns.VarVector("arg", origIndexTypes, Gen); Contract.Assert(cce.NonNullElements(typedArgs)); List<VCExprVar/*!*/> indexes = HelperFuns.VarVector("x", indexTypes, Gen); Contract.Assert(cce.NonNullElements(indexes)); Contract.Assert(typedArgs.Count == indexes.Count); inParams.AddRange(typedArgs); quantifiedVars.AddRange(indexes); for (int i = 0; i < arity; i++) { bindings.VCExprVarBindings.Add(typedArgs[i], indexes[i]); } // bound variable: val VCExprVar typedVal = Gen.Variable("val", mapResult); VCExprVar val = Gen.Variable("val", cce.NonNull(select.OutParams[0]).TypedIdent.Type); quantifiedVars.Add(val); bindings.VCExprVarBindings.Add(typedVal, val); // add all type parameters into bindings foreach (TypeVariable tp in implicitTypeParamsSelect) { VCExprVar tVar = Gen.Variable(tp.Name, AxBuilderPremisses.T); bindings.TypeVariableBindings.Add(tp, tVar); } List<VCExpr/*!*/> typeParams = new List<VCExpr/*!*/>(explicitTypeParamsSelect.Count); foreach (TypeVariable tp in explicitTypeParamsSelect) { VCExprVar tVar = Gen.Variable(tp.Name, AxBuilderPremisses.T); bindings.TypeVariableBindings.Add(tp, tVar); // ... and record these explicit type-parameter arguments in typeParams typeParams.Add(tVar); } VCExpr/*!*/ storeExpr = Store(store, m, indexes, val); Contract.Assert(storeExpr != null); VCExpr/*!*/ selectExpr = Select(select, typeParams, storeExpr, indexes); Contract.Assert(selectExpr != null); // Create let-binding definitions for all type parameters. // The implicit ones can be phrased in terms of the types of the ordinary in-parameters, and // we want to make sure that they don't get phrased in terms of the out-parameter, so we pass // in inParams here. List<VCExprLetBinding/*!*/> letBindings_Implicit = AxBuilderPremisses.GenTypeParamBindings(implicitTypeParamsSelect, inParams, bindings, false); Contract.Assert(cce.NonNullElements(letBindings_Implicit)); // The explicit ones, by definition, can only be phrased in terms of the result, so we pass // in List(typedVal) here. List<VCExprLetBinding/*!*/> letBindings_Explicit = AxBuilderPremisses.GenTypeParamBindings(explicitTypeParamsSelect, HelperFuns.ToList(typedVal), bindings, false); Contract.Assert(cce.NonNullElements(letBindings_Explicit)); // generate: select(store(m, indices, val)) == val VCExpr/*!*/ eq = Gen.Eq(selectExpr, val); Contract.Assert(eq != null); // generate: type(val) == T, where T is the type of val VCExpr/*!*/ ante = Gen.Eq( AxBuilderPremisses.TypeOf(val), AxBuilderPremisses.Type2Term(mapResult, bindings.TypeVariableBindings)); Contract.Assert(ante != null); VCExpr body; if (CommandLineOptions.Clo.TypeEncodingMethod == CommandLineOptions.TypeEncoding.None || !AxBuilder.U.Equals(cce.NonNull(select.OutParams[0]).TypedIdent.Type)) { body = Gen.Let(letBindings_Explicit, eq); } else { body = Gen.Let(letBindings_Implicit, Gen.Let(letBindings_Explicit, Gen.ImpliesSimp(ante, eq))); } return Gen.Forall(quantifiedVars, new List<VCTrigger/*!*/>(), "mapAx0:" + select.Name, 0, body); }