示例#1
0
            // 'xmldocument$'(['xmldecl$'([version=1.0,encoding=ISO-8859-1])], ...]), [])
            static Encoding GetEncodingFromTerm(BaseTerm t, Encoding defEnc)
            {
                if (t.Arity == 0 || (t = t.Arg(0)).FunctorToString != XMLDECL)
                {
                    return(defEnc);
                }

                if (!((t = t.Arg(0)) is ListTerm)) // attributes last, find encoding
                {
                    return(defEnc);
                }

                foreach (BaseTerm b in (ListTerm)t)
                {
                    if (!(b is OperatorTerm) || !((OperatorTerm)b).HasBinaryOperator("="))
                    {
                        return(defEnc);
                    }

                    OperatorTerm ot = (OperatorTerm)b;

                    if (ot.Arg(0).FunctorToString == "encoding")
                    {
                        return(GetEncodingFromString(ot.Arg(1).FunctorToString));
                    }
                }

                return(defEnc);
            }
            public void Assert(BaseTerm assertion, bool asserta)
            {
                BaseTerm       head;
                TermNode       body = null;
                PredicateDescr pd;

                if (assertion.HasFunctor(PrologParser.IMPLIES))
                {
                    head = assertion.Arg(0);
                    body = assertion.Arg(1).ToGoalList();
                }
                else
                {
                    head = assertion;
                }

                if (!head.IsCallable)
                {
                    IO.Error("Illegal predicate head '{0}'", head.ToString());
                }

                string key = head.Key;

                if ((predefineds.Contains(key)) || (head.Precedence >= 1000))
                {
                    IO.Error("assert/1 cannot be applied to predefined predicate or operator '{0}'",
                             assertion.Index);
                }

                predTable.TryGetValue(key, out pd);
                ClauseNode newC = new ClauseNode(head, body);

                if (pd == null) // first head
                {
                    SetClauseList(head.FunctorToString, head.Arity, newC);
                    ResolveIndices();
                }
                else if (pd.IsCacheable)
                {
                    IO.Error("assert/1 cannot be applied to cached predicate '{0}'",
                             assertion.Index);
                }
                else if (asserta)                    // at beginning
                {
                    newC.NextClause = pd.ClauseList; // pd.ClauseList may be null
                    SetClauseList(head.FunctorToString, head.Arity, newC);
#if arg1index
                    pd.CreateFirstArgIndex(); // re-create
#endif
                }
                else // at end
                {
                    pd.AppendToClauseList(newC);
#if arg1index
                    pd.CreateFirstArgIndex(); // re-create
#endif
                }

                InvalidateCrossRef();
            }
示例#3
0
        static void DoJsonPair(JsonTextBuffer avb, BaseTerm t, bool first)
        {
            if (!(t.FunctorToString == ":" && t.Arity == 2))
            {
                IO.Error("Not a JSON-term:\r\n{0}", t);
            }

            DoJsonValue(avb, t.Arg(0).FunctorToString, t.Arg(1), first);
        }
示例#4
0
            public void SetDiscontiguous(BaseTerm t)
            {
                if (t == null || t.FunctorToString != SLASH || !t.Arg(0).IsAtom || !t.Arg(1).IsInteger)
                {
                    IO.Error("Illegal or missing argument '{0}' for discontiguous/1", t);
                }

                // The predicate descriptor does not yet exist (and may even not come at all!)
                string key = BaseTerm.MakeKey(t.Arg(0).FunctorToString, t.Arg(1).To <short>());

                //IO.WriteLine ("--- Setting discontiguous for {0} in definitionFile {1}", key, Globals.ConsultFileName);
                isDiscontiguous[key] = "true";
            }
示例#5
0
            static void SingleContentListElement(XmlTextWriter xwr, NodePath nodePath, BaseTerm e)
            {
                string type = e.FunctorToString;

                try
                {
                    if (e is AtomTerm)
                    {
                        xwr.WriteRaw(e.FunctorToString.Dequoted());
                    }
                    else if (e is StringTerm || e is DecimalTerm || (e is OperatorTerm && e.Arity == 0))
                    {
                        xwr.WriteString(e.FunctorToString);
                    }
                    else if (e is NamedVariable)
                    {
                        IO.Error("ContentTermToXml -- Term contains uninstantiated variable '{0}'", e);
                    }
                    else if (!(e is AnonymousVariable)) // anon: don't do anything (no content)
                    {
                        switch (type)
                        {
                        case XMLDECL:
                            xwr.WriteStartDocument(true);
                            break;

                        case CDATA:
                            xwr.WriteCData(e.Arg(0).FunctorToString);
                            break;

                        case COMMENT:
                            xwr.WriteComment(e.Arg(0).FunctorToString);
                            break;

                        case INSTRUCTIONS:
                            xwr.WriteProcessingInstruction(e.Arg(0).FunctorToString, e.Arg(1).ToString());
                            break;

                        default:
                            ElementTermToXml(xwr, e, nodePath);
                            break;
                        }
                    }
                }
                catch (Exception x)
                {
                    throw new ApplicationException(
                              string.Format("Error in SingleContentListElement:\r\n{0}", x.Message));
                }
            }
示例#6
0
 static void ContentTermToXml(XmlTextWriter xwr, BaseTerm contentList, NodePath nodePath) // process element content
 {
     if (contentList is ListTerm)
     {
         while (!contentList.IsEmptyList) // traverse ...
         {
             SingleContentListElement(xwr, nodePath, contentList.Arg(0));
             contentList = contentList.Arg(1);
         }
     }
     else
     {
         SingleContentListElement(xwr, nodePath, contentList);
     }
 }
示例#7
0
            public static bool SetWorkingDirectory(BaseTerm term, VarStack varStack)
            {
                if (term.Arity == 0)
                {
                    workingDirectory = GetConfigSetting("WorkingDirectory", null);
                    IO.Message("Working directory set to '{0}'", WorkingDirectory);

                    return(true);
                }

                BaseTerm t0 = term.Arg(0);

                if (t0.IsVar)
                {
                    t0.Unify(new StringTerm(workingDirectory), varStack); // symbolic names

                    return(true);
                }

                string wd = Utils.DirectoryNameFromTerm(t0);

                if (wd == null)
                {
                    IO.Error("Illegal name '{0}' for working directory", t0.FunctorToString);

                    return(false);
                }

                workingDirectory = wd;
                IO.Message("Working directory set to '{0}'", WorkingDirectory);

                return(true);
            }
            void DoJsonPair(BaseTerm t) // <string> ':' <value>
            {
                if (t.Arity < 2)
                {
                    IO.Error("Not a well-formed JSON-term: {0}", t.ToString());
                }

                DoJsonLiteral(t.Arg(0));
                jtb.EmitString(": ");
                BaseTerm arg1 = t.Arg(1);

                if (arg1.Arity == 0)
                {
                    DoJsonLiteral(arg1);
                }
                else
                {
                    jtb.Newline();
                    DoJsonValue(arg1);
                }
            }
示例#9
0
        static void DoJsonPair(XmlTextWriter xwr, string [] attributes, BaseTerm t, ref bool contentWritten)
        {
            if (!(t.FunctorToString == ":" && t.Arity == 2))
            {
                IO.Error("Unable to convert term to XML:\r\n{0}", t);
            }

            string label = t.Arg(0).FunctorToString;

            if (!contentWritten && t.Arg(1).Arity == 0 && attributes != null && attributes.Contains(label))
            {
                xwr.WriteAttributeString(label, t.Arg(1).FunctorToString);
            }
            else
            {
                xwr.WriteStartElement(label);
                contentWritten = false;
                DoJsonValue(xwr, attributes, label, t.Arg(1), ref contentWritten);
                xwr.WriteEndElement();
                contentWritten = true;
            }
        }
            // put the predicate definition (if found) into the TermNode if it is not already there
            public bool FindPredicateDefinition(PredicateTable predicateTable)
            {
                if (predDescr == null)
                {
                    //IO.WriteLine ("predDescr == null for {0}", term.Name);
                    if ((predDescr = predicateTable [term.Key]) == null)
                    {
                        return(false);
                    }
                }

#if arg1index // first-argument indexing enabled
                BaseTerm arg;

                // caching would disturb the search process (since caching does not
                // cause the arg0Index to be rebuild, since this might be to costly)
                if (predDescr.IsFirstArgIndexed && !predDescr.HasCachedValues)
                {
                    if ((arg = term.Arg(0)).IsVar)
                    {
                        nextClause = predDescr.FirstArgVarClause();
                    }
                    else // not a variable
                    {
                        nextClause = predDescr.FirstArgNonvarClause(arg.FunctorToString);

                        // check whether there is an indexed var clause
                        if (nextClause == null)
                        {
                            nextClause = predDescr.FirstArgVarClause();
                        }

                        // if the above failed, the entire predicate fails (no unification possible)
                        if (nextClause == null)
                        {
                            nextClause = ClauseNode.FAIL;
                        }
                    }

                    if (nextClause == null)
                    {
                        nextClause = predDescr.ClauseList;
                    }
                }
                else // not indexed
#endif
                nextClause = predDescr.ClauseList;

                return(true);
            }
示例#11
0
 void DoJsonStruct(BaseTerm t) // object or array
 {
     if (t.FunctorToString == "array")
     {
         DoJsonArray(t.Arg(0));
     }
     else if (t.IsProperList)
     {
         DoJsonObject(t);
     }
     else
     {
         IO.Error("Not a well-formed JSON-term: {0}", t.ToString());
     }
 }
示例#12
0
            public bool SetSpy(bool enabled, string functor, int arity, BaseTerm list)
            {
                SpyPort ports;

                if (list == null)
                {
                    ports = SpyPort.Full;
                }
                else
                {
                    ports = SpyPort.None;
                    string s;

                    while (list.Arity == 2)
                    {
                        s = list.Arg(0).FunctorToString;

                        try
                        {
                            ports |= (SpyPort)Enum.Parse(typeof(SpyPort), s);
                        }
                        catch
                        {
                            IO.Error("Illegal value '{0}'", s);
                        }
                        list = list.Arg(1);
                    }
                }

                PredicateDescr pd;

                if (arity == -1)
                {
                    bool found = false;

                    foreach (KeyValuePair <string, PredicateDescr> kv in predTable)
                    {
                        if ((pd = kv.Value).Functor == functor)
                        {
                            found = true;
                            pd.SetSpy(enabled, pd.Functor, pd.Arity, ports, !enabled);
                        }
                    }

                    if (!found)
                    {
                        IO.Error("Predicate does not exist: {0}", functor);
                    }

                    return(found);
                }
                else
                {
                    predTable.TryGetValue(BaseTerm.MakeKey(functor, arity), out pd);

                    if (pd == null)
                    {
                        IO.Error("Predicate does not exist: {0}/{1}", functor, arity);

                        return(false);
                    }

                    pd.SetSpy(enabled, functor, arity, ports, !enabled);
                }

                return(true);
            }
            // xmlTerm = xmldocument( [<xmlprolog>?], element (...), [<misc>?])
            // Conversion of a Prolog BaseTerm to an XML-structure (in a string or in a file)
            public static void TermToXml(BaseTerm settings, BaseTerm xmlTerm, ref string fileNameOrXmlString)
            {
                // get settings
                bool isXChars = true;
                bool isRemPrf = false;
                bool isDtdChk = false;
                bool isIndent = true;
                Encoding encoding = null;
                string settingValue = null; // value of setting

                if (settings != null)
                  foreach (BaseTerm setting in (ListTerm)settings) // traverse settings
                  {
                string settingName = setting.FunctorToString;

                if (setting.Arity == 1)
                  settingValue = setting.Arg (0).FunctorToString;
                else
                  IO.Error ("Illegal setting in xml_term/3: '{0}'", setting);

                switch (settingName)
                {
                  case "extended_characters": // Use the extended character entities for XHTML (default true)
                isXChars = (settingValue == "true");
                break;
                  case "remove_attribute_prefixes": // Remove namespace prefixes from attributes when it
                // is the same as the prefix of the parent element
                isRemPrf = (settingValue == "true");
                break;
                  case "indent": // Indent the element content (2 spaces)
                isIndent = (settingValue == "true");
                break;
                  case "encoding": // Encoding to appear in XML-declaration
                encoding = GetEncodingFromString (settingValue);
                break;
                  case "check_dtd": // Read the referenced DTD
                isDtdChk = (settingValue == "true");
                break;
                  default:
                IO.Error ("Unknown setting in xml_term/3: '{0}'", setting);
                break;
                }
                  }

                XmlTextWriter xwr = null;
                StringWriter sw = new StringWriter ();

                try
                {
                  BaseTerm t0 = xmlTerm.Arg (0);

                  if (fileNameOrXmlString == null) // return flat XmlString
                  {
                xwr = new XmlTextWriter (sw);
                xwr.Formatting = Formatting.None;
                  }
                  else // write to file
                  {
                // get the encoding from the term
                if (encoding == null)
                  encoding = GetEncodingFromTerm (t0, Encoding.UTF8); // if not provided use Encoding.UTF8

                xwr = new XmlTextWriter (fileNameOrXmlString, encoding);
                xwr.Formatting = isIndent ? Formatting.Indented : Formatting.None;
                xwr.Indentation = 2;
                xwr.IndentChar = ' '; // default
                xwr.Namespaces = true;
                ContentTermToXml (xwr, t0);
                  }

                  ElementTermToXml (xwr, xmlTerm.Arg (1)); // top-level element
                }
                catch (Exception e)
                {
                  IO.Error ("Unable to convert term to XML:\r\n{0}\r\n\r\nMessage was:\r\n{1}", xmlTerm, e.Message);
                }
                finally
                {
                  if (fileNameOrXmlString == null)
                fileNameOrXmlString = sw.ToString ();
                  else if (xwr != null)
                xwr.Close ();
                }
            }
            // process an element content, i.e. a t
            static void ContentTermToXml(XmlTextWriter xwr, BaseTerm list)
            {
                while (!list.IsEmptyList) // traverse ...
                {
                  BaseTerm e = list.Arg (0);
                  string type = e.FunctorToString;

                #if !fullyTagged
                  if (e is StringTerm)
                xwr.WriteString (((StringTerm)e).Value);
                  else if (e is DecimalTerm)
                xwr.WriteString (((DecimalTerm)e).FunctorToString);
                  else if (e is CompoundTerm)
                ElementTermToXml (xwr, e);
                  else
                #endif
                switch (type)
                {
                  case XMLDECL:
                xwr.WriteStartDocument (true);
                break;
                #if fullyTagged
                case ELEMENT:
                  if (!ElementTermToXml (xwr, e)) return false;
                  break;
                case TEXT:
                  xwr.WriteString (e.Arg (0).FunctorToString);
                  break;
                #endif
                  case CDATA:
                xwr.WriteCData (e.Arg (0).FunctorToString);
                break;
                  case COMMENT:
                xwr.WriteComment (e.Arg (0).FunctorToString);
                break;
                  case INSTRUCTIONS:
                xwr.WriteProcessingInstruction (e.Arg (0).FunctorToString, e.Arg (1).ToString ());
                break;
                  default:
                IO.Error ("ContentTermToXml -- unhandled type: {0} ({1})",
                  e.GetType ().Name, type);
                break;
                }

                  list = list.Arg (1);
                }
            }
            // process an element( <tag>, <attributes>, <content>)
            static void ElementTermToXml(XmlTextWriter xwr, BaseTerm e)
            {
                #if fullyTagged
                int ft = 1;
                #else
                int ft = 0;
                #endif
                // open tag
                if (e.Arity == 1 + ft && e.FunctorToString == XMLDECL)
                {
                  xwr.WriteStartDocument ();
                }
                else if (e.Arity == 2 + ft)
                {
                #if fullyTagged
                  xwr.WriteStartElement (e.Arg (0).ToString ().Dequoted ());
                #else
                  xwr.WriteStartElement (e.FunctorToString.Dequoted ());
                #endif

                  // attributes
                  BaseTerm le = e.Arg (ft); // t with attribute-value pairs

                  while (!le.IsEmptyList)
                  {
                BaseTerm av = le.Arg (0); // BaseTerm: attr = value
                xwr.WriteAttributeString (av.Arg (0).FunctorToString.Dequoted (), av.Arg (1).FunctorToString);
                le = le.Arg (1);
                  }

                  // content
                  ContentTermToXml (xwr, e.Arg (1 + ft));
                  xwr.WriteEndElement ();
                }
                else
                  IO.Error ("Unexpected element encountered:\r\n{0}", e);
            }
示例#16
0
            static void ElementTermToXml(XmlTextWriter xwr, BaseTerm e, NodePath nodePath) // process an element( <tag>, <attributes>, <content>)
            {
                // open tag
                try
                {
                    if (e.Arity == 0)
                    {
                        IO.Error("ElementTermToXml -- unexpected zero-arity argument '{0}' ", e);
                    }
                    if (e.Arity == 1 && e.FunctorToString == XMLDECL)
                    {
                        xwr.WriteStartDocument();
                    }
                    else if (e.Arity <= 2)
                    {
                        string tag;
                        tag = e.FunctorToString.Dequoted();
                        nodePath.Push(tag);
                        xwr.WriteStartElement(tag);

                        if (e.Arity == 2) // process attributes
                        {
                            // attributes
                            BaseTerm le = e.Arg(0); // term with attribute-value pairs

                            if (!le.IsProperList)
                            {
                                IO.Error("Attribute-value pairs argument '{0}' is not a list", le);
                            }

                            while (!le.IsEmptyList)
                            {
                                if (le.Arity == 0)
                                {
                                    IO.Error("Wrong format for list of attribute-value pairs: {0}", le);
                                }

                                BaseTerm av = le.Arg(0); // BaseTerm: attr = value

                                if (av.Arity < 2)
                                {
                                    IO.Error("Wrong format for attribute-value pair: {0}", av);
                                }

                                xwr.WriteAttributeString(
                                    av.Arg(0).FunctorToString.Dequoted(),
                                    av.Arg(1).FunctorToString.Dequoted());
                                le = le.Arg(1);
                            }
                        }

                        // content
                        ContentTermToXml(xwr, e.Arg(e.Arity - 1), nodePath);
                        xwr.WriteEndElement();
                    }
                    else
                    {
                        IO.Error("Unexpected element encountered:\r\n{0}", e);
                    }

                    nodePath.Pop();
                }
                catch (Exception x)
                {
                    throw new ApplicationException(
                              string.Format("Error in ElementTermToXml:\r\n{0}", x.Message));
                }
            }
示例#17
0
            // Conversion of a Prolog BaseTerm to an XML-structure (in a string or in a file)
            public static void TermToXml(BaseTerm settings, BaseTerm xmlTerm, ref string fileNameOrXmlString)
            // xmlTerm = 'xmldocument$'( [<xmlprolog>?], element (...), [<misc>?])
            {
                // get settings
                bool     isXChars     = true;
                bool     isRemPrf     = false;
                bool     isDtdChk     = false;
                bool     isIndent     = true;
                Encoding encoding     = null;
                string   settingValue = null; // value of setting
                NodePath nodePath     = new NodePath();

                if (settings != null)
                {
                    foreach (BaseTerm setting in (ListTerm)settings) // traverse settings
                    {
                        string settingName = setting.FunctorToString;

                        if (setting.Arity == 1)
                        {
                            settingValue = setting.Arg(0).FunctorToString;
                        }
                        else
                        {
                            IO.Error("Illegal setting in xml_term/3: '{0}'", setting);
                        }

                        switch (settingName)
                        {
                        case "extended_characters": // Use the extended character entities for XHTML (default true)
                            isXChars = (settingValue == "true");
                            break;

                        case "remove_attribute_prefixes": // Remove namespace prefixes from attributes when it
                            // is the same as the prefix of the parent element
                            isRemPrf = (settingValue == "true");
                            break;

                        case "indent": // Indent the element content (2 spaces)
                            isIndent = (settingValue == "true");
                            break;

                        case "encoding": // Encoding to appear in XML-declaration
                            encoding = GetEncodingFromString(settingValue);
                            break;

                        case "check_dtd": // Read the referenced DTD
                            isDtdChk = (settingValue == "true");
                            break;

                        default:
                            IO.Error("Unknown setting in xml_term/3: '{0}'", setting);
                            break;
                        }
                    }
                }

                XmlTextWriter xwr = null;
                StringWriter  sw  = new StringWriter();

                try
                {
                    if (fileNameOrXmlString == null) // return flat XmlString. Encoding etc. not possible
                    {
                        xwr            = new XmlTextWriter(sw);
                        xwr.Formatting = Formatting.None;
                        xwr.QuoteChar  = '\'';
                    }
                    else // write to file
                    {
                        // get the encoding from the term
                        if (encoding == null)
                        {
                            encoding = GetEncodingFromTerm(xmlTerm.Arg(0), Encoding.UTF8); // if not provided use Encoding.UTF8
                        }
                        xwr             = new XmlTextWriter(fileNameOrXmlString, encoding);
                        xwr.Formatting  = isIndent ? Formatting.Indented : Formatting.None;
                        xwr.Indentation = 2;
                        xwr.IndentChar  = ' '; // default
                        xwr.QuoteChar   = '\'';
                        xwr.Namespaces  = true;
                    }

                    if (xmlTerm.FunctorToString == XMLDOCUMENT)
                    {
                        xmlTerm = xmlTerm.Arg(1);
                    }

                    ElementTermToXml(xwr, xmlTerm, nodePath); // top-level element
                }
                catch (Exception x)
                {
                    string s = nodePath.ToString();

                    IO.Error("Unable to convert term to XML:\r\n{0}{1}\r\n\r\nMessage was:\r\n{1}{2}", xmlTerm, x.Message,
                             (s == null) ? null : string.Format("\r\n\r\nNode path was {0}", s));
                }
                finally
                {
                    if (fileNameOrXmlString == null)
                    {
                        fileNameOrXmlString = sw.ToString();
                    }
                    else if (xwr != null)
                    {
                        xwr.Close();
                    }
                }
            }
            // 'xmldocument$'(['xmldecl$'([version=1.0,encoding=ISO-8859-1])], ...]), [])
            static Encoding GetEncodingFromTerm(BaseTerm t, Encoding defEnc)
            {
                if (t.Arity == 0 || (t = t.Arg (0)).FunctorToString != XMLDECL)
                  return defEnc;

                if (!((t = t.Arg (0)) is ListTerm)) // attributes last, find encoding
                  return defEnc;

                foreach (BaseTerm b in (ListTerm)t)
                {
                  if (!(b is OperatorTerm) || !((OperatorTerm)b).HasBinaryOperator ("="))
                return defEnc;

                  OperatorTerm ot = (OperatorTerm)b;

                  if (ot.Arg (0).FunctorToString == "encoding")
                return GetEncodingFromString (ot.Arg (1).FunctorToString);
                }

                return defEnc;
            }