internal IEnumerable <Clause> UnifyClauses(Goal g) { var any = false; //g = Goal.From(g.Term.ReplaceArguments((i, a) => a switch { _ => new Variable("_", Maybe.Some(a)) })) // .ValueOrThrow(""); var gFunc = g.Term switch { CompoundTerm c => c.Functor, AtomicTerm a => a.Atom, _ => null }; foreach (var clause in Data) { var hFunc = clause.Head.Term switch { CompoundTerm c => c.Functor, AtomicTerm a => a.Atom, _ => null }; var head = clause.Head.Term;//.ReplaceArguments((i, a) => a switch { _ => new Variable("_", Maybe.Some(a)) }); any |= gFunc.UnifyWith(hFunc).TryGetValue(out _); if (g.Term.UnifyWith(head).TryGetValue(out var w)) { yield return(ReplaceVariables(clause, Fact.From(w).ValueOrThrow(""))); } else if (head.UnifyWith(g.Term).TryGetValue(out var u)) { yield return(ReplaceVariables(clause, Fact.From(u).ValueOrThrow(""))); } } if (!any) { throw new UndefinedPredicateException(new Clause(g, new List <Goal>()).Canonical()); } }
public CompoundTerm DoAction(CompoundTerm action) { switch (action.FunctionSymbol.ToString()) { case ("Tests"): return(null); // first action in test seq. case ("SelectMessages"): NewsReaderUI.SelectMessages(); return(null); case ("SelectTopics"): NewsReaderUI.SelectTopics(); return(null); case ("ShowTitles"): NewsReaderUI.ShowTitles(); return(null); case ("ShowText"): NewsReaderUI.ShowText(); return(null); case ("SortByFirst"): NewsReaderUI.SortByFirst(); return(null); case ("SortByMostRecent"): NewsReaderUI.SortByMostRecent(); return(null); default: throw new Exception("Unexpected action " + action); } }
/// <summary> /// Produces the target state that results from invoking <paramref name="action"/> /// in the context of <paramref name="startState"/>. /// </summary> /// <param name="startState">The state in which the action is invoked</param> /// <param name="action">The action to be invoked</param> /// <param name="transitionPropertyNames">The names of meta-properties to be collected /// during the calculation of the step.</param> /// <param name="transitionProperties">Output parameter that will contain a /// map of property names to property values. Each property value multiset of /// terms. For example, the property value might be the value of a Boolean function /// that controls state filtering. Or, it might correspond to the "coverage" of the model that results from this /// step. In this case, the value might denote the line numbers or blocks of the /// model program that were exercised in this step, or a projection of the state /// space or a reference to section numbers of a requirements document to indicate /// that the functionality defined by that section was exercised.</param> /// <returns>The state that results from the invocation of <paramref name="action"/> /// in <paramref name="startState"/>.</returns> /// <seealso cref="GetTransitionPropertyNames"/> public override IState GetTargetState(IState startState, CompoundTerm action, Set <string> transitionPropertyNames, out TransitionProperties transitionProperties) { // it is assumed that the action is enabled in the given state PairState ps = startState as PairState; if (ps == null) { throw new ArgumentException("Unexpected type-- expected PairState"); } Symbol actionSymbol = action.Symbol; if (!this.signature.Contains(actionSymbol)) { throw new ArgumentException("Invalid argument-- action symbol " + actionSymbol.ToString() + " not in signature."); } bool doM1 = this.signature.IsShared(actionSymbol) || this.signature.IsOnlyInM1(actionSymbol); bool doM2 = this.signature.IsShared(actionSymbol) || this.signature.IsOnlyInM2(actionSymbol); TransitionProperties m1TransitionProperties = new TransitionProperties(); TransitionProperties m2TransitionProperties = new TransitionProperties(); IState targetState1 = doM1 ? m1.GetTargetState(M1Reduct(ps), action, transitionPropertyNames, out m1TransitionProperties) : M1Reduct(ps); IState targetState2 = doM2 ? m2.GetTargetState(M2Reduct(ps), action, transitionPropertyNames, out m2TransitionProperties) : M2Reduct(ps); transitionProperties = m1TransitionProperties.Union(m2TransitionProperties); return(PairState.CreateState(targetState1, targetState2)); }
internal Set <CompoundTerm> processGoal(ModelProgram mp, Set <CompoundTerm> goals) { Set <CompoundTerm> processedGoals = Set <CompoundTerm> .EmptySet; if (typeof(LibraryModelProgram) == mp.GetType()) { //we ignore it for the moment Console.Error.WriteLine("Goals involving LibraryModelPrograms currently not supported. "); Console.Error.WriteLine("Currently searching for a match for '" + goals.ToString() + "'. "); } else if (typeof(FsmModelProgram) == mp.GetType()) { FsmModelProgram fsm = (FsmModelProgram)mp; foreach (CompoundTerm ct in goals) { Console.WriteLine("Checking FSM: " + ct.ToString() + "; " + fsm.Name); if (ct.FunctionSymbol.ToString() == fsm.Name) { processedGoals = processedGoals.Add(CompoundTerm.Parse("FsmState(Set(" + ct.Arguments[0].ToString() + "))")); goals = goals.Remove(ct); } Console.WriteLine("Current processedGoals: " + processedGoals.ToString()); } } else if (typeof(ProductModelProgram) == mp.GetType()) { ProductModelProgram pmp = (ProductModelProgram)mp; processedGoals = processedGoals.Union(processGoal(pmp.M1, goals)); processedGoals = processedGoals.Union(processGoal(pmp.M2, goals)); } return(processedGoals); }
/// <summary> /// Process the goal in the format "ModelProgramName1(stateName1(value1)),ModelProgramName2(stateName2(value2)" to a compound term of the corresponding model program. /// In the case of FSMs the format is "ModelProgramName(stateNumber)". /// </summary> /// <param name="mp">model program</param> /// <param name="goalString">goal as string</param> /// <returns>A set of compound terms corresponding to the goal string.</returns> internal Set <CompoundTerm> processGoal(ModelProgram mp, string goalString) { Set <CompoundTerm> processedGoals = Set <CompoundTerm> .EmptySet; if (goalString == "") { return(processedGoals); } string[] subgoals = goalString.Split(','); Set <CompoundTerm> goals = Set <CompoundTerm> .EmptySet; try { foreach (string g in subgoals) { CompoundTerm ct = CompoundTerm.Parse(g); goals = goals.Add(ct); } } catch (Exception e) { Console.Error.WriteLine("The goal '" + goalString + "' seems not to be a term. " + "Goal should be in the form ModelProgramName(state) " + "(or several such terms separated by commas)."); Console.Error.WriteLine("The error message: ", e.Message); return(processedGoals); } return(processGoal(mp, goals)); }
private void JsonArray(TerminalSet _TS, out BaseTerm t) { BaseTerm e; List <BaseTerm> listItems = new List <BaseTerm> (); GetSymbol(new TerminalSet(terminalCount, LSqBracket), true, true); GetSymbol(new TerminalSet(terminalCount, IntLiteral, RealLiteral, StringLiteral, LSqBracket, RSqBracket, LCuBracket, TrueSym, FalseSym, NullSym), false, true); if (symbol.IsMemberOf(IntLiteral, RealLiteral, StringLiteral, LSqBracket, LCuBracket, TrueSym, FalseSym, NullSym)) { while (true) { JsonValue(new TerminalSet(terminalCount, Comma, RSqBracket), out e); listItems.Add(e); GetSymbol(new TerminalSet(terminalCount, Comma, RSqBracket), false, true); if (symbol.TerminalId == Comma) { symbol.SetProcessed(); } else { break; } } } GetSymbol(new TerminalSet(terminalCount, RSqBracket), true, true); t = new CompoundTerm("array", ListTerm.ListFromArray(listItems.ToArray(), BaseTerm.EMPTYLIST)); }
/// <summary> /// Returns true if the action is enabled in the given state /// </summary> public override bool IsEnabled(IState state, CompoundTerm action) //^ requires IsPotentiallyEnabled(state, action.FunctionSymbol1); { PairState ps = state as PairState; if (ps == null) { throw new ArgumentException("Unexpected type-- expected PairState"); } if (action == null) { throw new ArgumentNullException("action"); } Symbol actionSymbol = action.Symbol; if (this.signature.IsShared(actionSymbol)) { return(m1.IsEnabled(M1Reduct(ps), action) && m2.IsEnabled(M2Reduct(ps), action)); } else if (this.signature.IsOnlyInM1(actionSymbol)) { return(m1.IsEnabled(M1Reduct(ps), action)); } else if (this.signature.IsOnlyInM2(actionSymbol)) { return(m2.IsEnabled(M2Reduct(ps), action)); } else { throw new ArgumentException("Invalid argument-- action symbol " + actionSymbol.ToString() + " not in signature."); } }
new public CompoundTerm DoAction(CompoundTerm action) { if (svthread == null) { startServer(); } return(base.DoAction(action)); }
internal static void CallObserver(CompoundTerm action) { if (observer != null) { //System.Windows.Forms.MessageBox.Show(action.ToString()); observer(action); } }
internal static void PrivateReceive(Client sender, string message, Client receiver) { CompoundTerm action = new CompoundTerm(new Symbol("PrivateReceive"), new Sequence <Term>(Term.Parse(sender.Name), new Literal(message), Term.Parse(receiver.Name))); CallObserver(action); }
public static Variable[] Variables(this ICanonicalRepresentation obj) { return(obj switch { CompoundTerm c => c.Arguments.SelectMany(a => a.Variables()).ToArray(), Variable v => new[] { v }, Clause k => k.Head.Term.Variables().Union(k.Body.Goals.SelectMany(g => g.Term.Variables())).ToArray(), _ => Array.Empty <Variable>() });
/// <summary> /// Update the current state to the target state of the action from the current state. /// If the action is the current action in the current test case, consume that action. /// </summary> /// <param name="action">given action</param> public override void DoAction(CompoundTerm action) { base.DoAction(action); if (!this.currentTest.IsEmpty && this.currentTest.Head.Equals(action)) { this.currentTest = this.currentTest.Tail; this.currentTestInProgress = true; } }
internal SetViewer(string keyName, CompoundTerm t) { this.t = t; this.keyName = keyName; this.argumentViewers = new TermViewer[t.Arguments.Count]; for (int i = 0; i < t.Arguments.Count; i++) { argumentViewers[i] = Create("Member", t.Arguments[i]); } }
internal SequenceViewer(string keyName, CompoundTerm t) { this.t = t; this.keyName = keyName; this.argumentViewers = new TermViewer[t.Arguments.Count]; for (int i = 0; i < t.Arguments.Count; i++) { argumentViewers[i] = Create("Element " + i.ToString(MaxPositions(t.Arguments.Count)), t.Arguments[i]); } }
static bool IsStartAction(Term action) { CompoundTerm a = action as CompoundTerm; if (a == null) { return(false); } return(a.Name.EndsWith("_Start")); }
private Map <Variable, Term> ConstructSubst(CompoundTerm a, Sequence <Term> vars) { Map <Variable, Term> subst = Map <Variable, Term> .EmptyMap; for (int i = 0; i < vars.Count; i++) { subst = subst.Add((Variable)vars[i], a.Arguments[i]); } return(subst); }
internal static void Receive(Client sender, string message, Client receiver) { if (sender != receiver) //ignore messages sent back to the sender { CompoundTerm action = new CompoundTerm(new Symbol("Receive"), new Sequence <Term>(Term.Parse(sender.Name), new Literal(message), Term.Parse(receiver.Name))); CallObserver(action); } }
static bool IsFinishAction(Term action) { CompoundTerm a = action as CompoundTerm; if (a == null) { return(false); } return(a.Name.EndsWith("_Finish")); }
/// <summary> /// Constructs a model program from a (potentially) nondeterministic finite automaton. The internal /// states of the model program are chosen so that actions are deterministic. /// </summary> /// <param name="automaton">The underlying finite automaton that will provide the steps</param> /// <param name="modelName">A string identifying this model program</param> public FsmModelProgram(FSM automaton, string modelName) { Dictionary <Term, Set <Symbol> > potentiallyEnabled = new Dictionary <Term, Set <Symbol> >(); Dictionary <Symbol, int> actionArities = new Dictionary <Symbol, int>(); foreach (Transition transition in automaton.Transitions) { // collect action symbol CompoundTerm action = transition.Second as CompoundTerm; if (action == null) { throw new ArgumentException("Expected CompoundTerm, saw " + transition.Second.GetType().ToString()); } Symbol actionSymbol = action.Symbol; // collect arity int existingArity; if (!actionArities.TryGetValue(actionSymbol, out existingArity)) { actionArities.Add(actionSymbol, action.Arguments.Count); } else if (existingArity != action.Arguments.Count) { throw new ArgumentException("Inconsistent arity for action symbol " + actionSymbol.ToString()); } // collect potentially enabled Set <Symbol> actions1; if (!potentiallyEnabled.TryGetValue(transition.First, out actions1)) { actions1 = Set <Symbol> .EmptySet; } potentiallyEnabled[transition.First] = actions1.Add(actionSymbol); } if (automaton.Transitions.IsEmpty) { throw new ArgumentException("Finite automaton must contain at least one transition"); } foreach (Symbol sym in automaton.Vocabulary) { if (!actionArities.ContainsKey(sym)) { actionArities[sym] = 0; } } this.automaton = automaton; this.actionArities = actionArities; this.parameterDomains = new Dictionary <Parameter, Set <Term> >(); this.potentiallyEnabled = potentiallyEnabled; this.name = modelName; }
public override CompoundTerm DoStep(InterpretationContext c, CompoundTerm action) { // Result of invocation must be a value term (must support IComparable) IComparable /*?*/ thisArg; IComparable /*?*/[] methodArgs = this.ConvertTermArgumentsToMethodArguments(c, action.Arguments, out thisArg); foreach (IComparable /*?*/ o in methodArgs) { AbstractValue.FinalizeImport(o); } object /*?*/ resultObj = this.method.methodInfo.Invoke(thisArg, methodArgs); CompoundTerm /*?*/ finishAction = null; // Handle output args and return value if (null != this.finishActionMethod) { int nOutputs = this.finishActionMethod.actionLabel.Arguments.Count; Sequence <Term> outputs = Sequence <Term> .EmptySequence; for (int i = 0; i < nOutputs; i += 1) { int outputArgIndex = this.finishActionMethod.outputArgumentIndices[i]; if (-2 == outputArgIndex) // "any" placeholder { outputs = outputs.AddLast(Any.Value); } else { object output = (-1 == outputArgIndex ? resultObj : methodArgs[outputArgIndex]); IComparable outputAsComparable; if (null == output) { outputAsComparable = null; } else { outputAsComparable = output as IComparable; if (null == outputAsComparable) { throw new InvalidOperationException(MessageStrings.LocalizedFormat(MessageStrings.ComparableResultRequired, action.ToString(), output.ToString())); } } outputs = outputs.AddLast(AbstractValue.GetTerm(outputAsComparable)); } } finishAction = new CompoundTerm(this.FinishAction, outputs); } return(finishAction); }
/// <summary> /// Show the transition with the given action from the given state /// </summary> internal void ShowTransition(Node sourceNode, CompoundTerm action) { Node targetNode; if (TryGetTargetNode(sourceNode, action, out targetNode)) { Transition t = new Triple <Term, CompoundTerm, Term>(sourceNode, action, targetNode); this.transitions = this.transitions.Add(t); this.hiddenTransitions = this.hiddenTransitions.Remove(t); } }
private void UpdateCoveragePoints(CompoundTerm action) { int hash = this.currState.GetHashCode(); //System.Console.WriteLine("action taken "+ action.ToString()); if (!cps.ContainsKey(hash)) { cps[hash] = new Set <int>(); } cps[hash] = cps[hash].Add(action.GetHashCode()); }
internal MapViewer(string keyName, CompoundTerm t, bool isBag) { this.isBag = isBag; this.t = t; this.keyName = keyName; this.argumentViewers = new TermViewer[t.Arguments.Count / 2]; for (int i = 0; i < argumentViewers.Length; i++) { argumentViewers[i] = new MapletViewer(t.Arguments[2 * i], t.Arguments[(2 * i) + 1], isBag); } }
/// <summary> /// Computes the mapping from the parameter positions of the action label to the /// output parameter positions of the .NET method that implements the action. /// </summary> /// <param name="actionLabel">The finish action label</param> /// <param name="actionMethod">The action method</param> /// <returns>An array of integers where each entry is the index in the parameter list /// of the .NET method. The special value -1 is used to indicate the position of the the /// return value. The special value -2 is used to indicate an ignored argument.</returns> internal static int[] GetOutputParameterIndices(CompoundTerm actionLabel, MethodInfo actionMethod) { List <int> parameterIndices = new List <int>(); foreach (Term arg in actionLabel.Arguments) { if (Any.Value == arg) { parameterIndices.Add(-2); } else { Variable v = arg as Variable; if (null != v) { string name = v.ToString(); if ("result".Equals(name)) { parameterIndices.Add(-1); } else { int index = 0; bool foundMatch = false; foreach (ParameterInfo pInfo in actionMethod.GetParameters()) { if (pInfo.Name.Equals(name)) { parameterIndices.Add(index); foundMatch = true; break; } index += 1; } // this test is dead code (was previously checked). if (!foundMatch) { throw new ModelProgramUserException("action label " + actionLabel.ToString() + " includes unrecognized output argument " + name); } } } else { throw new ModelProgramUserException("action label " + actionLabel.ToString() + " may not include ground term " + arg.ToString()); } } } return(parameterIndices.ToArray()); }
// This method has side effects on this.stateMap, this.nodeMap, this.nodes, this.acceptingNodes, this.actionsExploredFromNode private bool TryGetTargetNode(Node sourceNode, CompoundTerm action, out Node targetNode) { IState targetState; if (this.actionsExploredFromNode.ContainsKey(sourceNode)) { if (!this.actionsExploredFromNode[sourceNode].TryGetValue(action, out targetNode)) { //this action has not been explored yet from the given node TransitionProperties transitionProperties; targetState = this.modelProgram.GetTargetState(stateMap[sourceNode], action, Set <string> .EmptySet, out transitionProperties); if (!this.nodeMap.TryGetValue(targetState, out targetNode)) { targetNode = new Literal(this.nodes.Count); this.stateMap[targetNode] = targetState; this.nodeMap[targetState] = targetNode; this.nodes = this.nodes.Add(targetNode); if (this.modelProgram.IsAccepting(targetState)) { this.acceptingNodes = this.acceptingNodes.Add(targetNode); } //if (!this.modelProgram.SatisfiesStateInvariant(targetState)) // this.errorNodes = this.errorNodes.Add(targetNode); } } else { targetState = this.stateMap[targetNode]; } } else //the state has not yet been explored at all { TransitionProperties transitionProperties; targetState = this.modelProgram.GetTargetState(stateMap[sourceNode], action, Set <string> .EmptySet, out transitionProperties); if (!this.nodeMap.TryGetValue(targetState, out targetNode)) { targetNode = new Literal(this.nodes.Count); this.stateMap[targetNode] = targetState; this.nodeMap[targetState] = targetNode; this.nodes = this.nodes.Add(targetNode); if (this.modelProgram.IsAccepting(targetState)) { this.acceptingNodes = this.acceptingNodes.Add(targetNode); } //if (!this.modelProgram.SatisfiesStateInvariant(targetState)) // this.errorNodes = this.errorNodes.Add(targetNode); } Dictionary <CompoundTerm, Node> actionsFromState = new Dictionary <CompoundTerm, Node>(); actionsFromState[action] = targetNode; this.actionsExploredFromNode[sourceNode] = actionsFromState; } return(this.modelProgram.SatisfiesStateFilter(targetState)); }
public void FSM2Dot1() { FSM fa = FSM.FromTerm(CompoundTerm.Parse(FSMTRIANGLE)); GraphParams gp = new GraphParams("Test1", fa); StringBuilder sb = DotWriter.ToDot(gp); string s = sb.ToString(); Regex r = new Regex("\\[ label = \"AssignColor\" \\];", RegexOptions.Multiline); int count = 0; count = r.Matches(s).Count; Assert.AreEqual(42, count); }
public CompoundTerm DoAction(CompoundTerm action) { switch (action.Name) { case ("Tests"): return(null); // first action in test seq. case ("ServerSocket"): s.Socket(); return(null); case ("ServerBind"): s.Bind(host, port); return(null); case ("ServerListen"): s.Listen(); return(null); case ("ServerAccept"): s.Accept(); return(null); case ("ServerReceive"): s.Receive(); return(null); case ("ServerSend"): // s.Send sends a double, not a string! s.Send((double)((Literal)action.Arguments[0]).Value); return(null); case ("ServerCloseConnection"): s.CloseConnection(); return(null); case ("ServerClose"): s.Close(); return(null); case ("ClientSocket"): c.Socket(); return(null); case ("ClientConnect"): c.Connect(host, port); return(null); case ("ClientSend"): c.Send("T"); return(null); case ("ClientReceive_Start"): // c.Receive returns a double, not a string return(CompoundTerm.Create("ClientReceive_Finish", c.Receive())); case ("ClientClose"): c.Close(); return(null); default: throw new Exception("Unexpected action " + action); } }
/// <summary> /// Add a relational (i.e. unordered) transition into the graph. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="label"></param> public void AddRelationalTransition(Vertex from, Vertex to, String label) { VertexData vd = vertexRecords[from]; CompoundTerm edgeLabel = new CompoundTerm(new Symbol(label), new Sequence <Term>()); if (vd.unorderedOutgoingEdges.ContainsKey(edgeLabel)) { vd.unorderedOutgoingEdges = vd.unorderedOutgoingEdges.Override(edgeLabel, vd.unorderedOutgoingEdges[edgeLabel].Add(to)); } else { vd.unorderedOutgoingEdges = vd.unorderedOutgoingEdges.Add(edgeLabel, new Set <Vertex>(to)); } }
public CompoundTerm Recharge(int id) { if (aliveRobots.Contains(id)) { power[id] = power[id] + 1.0; reward[id] = reward[id] - 1.5; Random r = new Random(); if (r.Next(0, 2) == 0) { return(new CompoundTerm(Symbol.Parse("Recharge"), CompoundTerm.Create("Robot", id))); } } return(null); }
void CreateVariableWiewers() { //view also the control mode of the root state if the product has more than one machine in it //the id of the composed state is -1 //if (leafStates.Count > 1) // termViewers.Add(TermViewer.Create("[Control Mode]", rootState.ControlMode), -1); for (int stateId = 0; stateId < this.leafStates.Count; stateId++) { IState leafState = this.leafStates[stateId]; //string modelName = this.modelNames[stateId]; //each state has a control mode, create a viewer for it if the controlMode is //not an empty sequence if (!leafState.ControlMode.ToCompactString().Equals("Sequence()")) { termViewers.Add(TermViewer.Create("[Control Mode]", leafState.ControlMode), stateId); } IExtendedState estate = leafState as IExtendedState; if (estate != null) { #region add the domain map viewer, skip this if there are no domains if (estate.DomainMap.Count > 0) { //StringBuilder sb = new StringBuilder(); Sequence <Term> args = Sequence <Term> .EmptySequence; foreach (Pair <Symbol, int> si in estate.DomainMap) { args = args.AddLast(new Literal(si.First.FullName)); args = args.AddLast(new Literal(si.Second)); } Symbol symb = Symbol.Parse("Map<String, Integer>"); Term domMap = new CompoundTerm(symb, args); termViewers.Add(TermViewer.Create("[Domain Map]", domMap), stateId); } #endregion //add a viewer for each state variable for (int j = 0; j < estate.LocationValuesCount; j++) { termViewers.Add(TermViewer.Create(estate.GetLocationName(j), estate.GetLocationValue(j)), stateId); } } } }
static BaseTerm ToTermEx(Node root) { BaseTerm [] args = new BaseTerm [3]; #if fullyTagged args [0] = new AtomTerm (root.TagName.ToAtom ()); #else string tagName = root.TagName.ToAtom (); #endif args [1] = ListTerm.EMPTYLIST; Decimal d; foreach (KeyValuePair<string, string> kv in root.Attributes) // XML Declaration { BaseTerm pair; if (Decimal.TryParse (kv.Value, styleAllowDecPnt, Utils.CIC, out d)) pair = new OperatorTerm (EqualOpDescr, new AtomTerm (kv.Key), new DecimalTerm (d)); else pair = new OperatorTerm (EqualOpDescr, new AtomTerm (kv.Key), new StringTerm (kv.Value)); args [1] = new ListTerm (pair, args [1]); } args [2] = ListTerm.EMPTYLIST; if (root.ChildNodes.Count > 0) { foreach (Node n in root.ChildNodes) { BaseTerm e; e = null; switch (n.type) { case XmlNodeType.Element: e = ToTermEx (n); break; case XmlNodeType.Comment: e = new CompoundTerm (COMMENT, new StringTerm (n.text.Trim ().EscapeDoubleQuotes ())); break; case XmlNodeType.Text: if (Decimal.TryParse (n.text, styleAllowDecPnt, Utils.CIC, out d)) #if fullyTagged e = new CompoundTerm (TEXT, new DecimalTerm (d)); else e = new CompoundTerm (TEXT, new StringTerm (n.text.Trim ().EscapeDoubleQuotes ())); #else e = new DecimalTerm (d); else e = new StringTerm (n.text.Trim ().EscapeDoubleQuotes ()); #endif break; case XmlNodeType.CDATA: e = new CompoundTerm (CDATA, new StringTerm (n.text.Trim ().EscapeDoubleQuotes ())); break; case XmlNodeType.ProcessingInstruction: e = new CompoundTerm ("processing_instruction", new AtomTerm (n.name.ToAtom ()), new StringTerm (n.text.Trim ().EscapeDoubleQuotes ())); break; case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: break;
// ToTerm results in term xml( Pre, Element, Post), where Pre and Post are lists with comments // and/or processing instructions that come before/after the top-level XML element. public BaseTerm ToTerm() { BaseTerm pre = ListTerm.EMPTYLIST; BaseTerm post = ListTerm.EMPTYLIST; BaseTerm t = null; Node topEl = null; foreach (Node n in childNodes) // array was constructed in reverse order, so top-level XML-element is entry 0. { switch (n.type) { case XmlNodeType.Element: topEl = n; break; case XmlNodeType.Comment: t = new CompoundTerm (COMMENT, new StringTerm (n.Text)); if (topEl == null) post = new ListTerm (t, post); else pre = new ListTerm (t, pre); break; case XmlNodeType.ProcessingInstruction: t = new CompoundTerm (INSTRUCTIONS, new AtomTerm (n.name.ToAtom ()), new AtomTerm (n.text.Trim ())); if (topEl == null) post = new ListTerm (t, post); else pre = new ListTerm (t, pre); break; } } BaseTerm xmlDecl = ListTerm.EMPTYLIST; foreach (KeyValuePair<string, string> kv in Attributes) // XML Declaration (acually a PI) was stored in Attributes { BaseTerm pair = new OperatorTerm (EqualOpDescr, new AtomTerm (kv.Key), new AtomTerm (kv.Value)); xmlDecl = new ListTerm (pair, xmlDecl); // [pre, arg2, ...] } if (!xmlDecl.IsEmptyList) // enhance term with XML Declaration { xmlDecl = new CompoundTerm (XMLDECL, xmlDecl); pre = new ListTerm (xmlDecl, pre); } BaseTerm content = ToTermEx (topEl); // Now process top-level Element return new CompoundTerm (XMLDOCUMENT, new BaseTerm [] { pre, content, post }); }