示例#1
0
#pragma warning disable 1573
        /// <inheritdoc cref="SwiPrologQuery(string)" />
        /// <summary>locating the predicate in the named module.</summary>
        /// <param name="module">locating the predicate in the named module.</param>
        public SwiPrologQuery(string module, string goal)
        {
            if (string.IsNullOrEmpty(goal))
            {
                throw new ArgumentNullException("goal");
            }
            if (string.IsNullOrEmpty(module))
            {
                _module = ModuleDefault;
            }
            else
            {
                _module = module;
            }

            var queryString = goal;

            try
            {
                // call read_term(Term_of_query_string, [variable_names(VN)]).
                // read_term_from_atom('noun(ş,C)', T, [variable_names(Vars)]).
                // befor 2014 with redirected IO-Streams (PlQuery_Old_Kill_unused)
                var           atom          = new SwiPrologTerm("'" + goal.Replace(@"\", @"\\").Replace("'", @"\'") + "'");
                SwiPrologTerm term          = SwiPrologTerm.Variable();
                SwiPrologTerm options       = SwiPrologTerm.Variable();
                SwiPrologTerm variablenames = SwiPrologTerm.Variable();
                SwiPrologTerm l             = SwiPrologTerm.Tail(options);
                l.Append(SwiPrologTerm.Compound("variable_names", variablenames));
                l.Close();
                var args = new SwiPrologTermVector(atom, term, options);
                if (!Call(_module, "read_term_from_atom", args))
                {
                    throw new SwiPrologLibraryException("Call read_term_from_atom/3 fails! goal:" + queryString);
                }

                // set list of variables and variable_names into _queryVariables
                foreach (SwiPrologTerm t in variablenames.ToList())
                {
                    // t[0]='=' , t[1]='VN', t[2]=_G123
                    _queryVariables.Add(new SwiPrologQueryVariable(t[1].ToString(), t[2]));
                }

                // Build the query
                _name = term.Name;

                // is ok e.g. for listing/0.
                // Check.Require(term.Arity > 0, "PlQuery(PlTerm t): t.Arity must be greater than 0.");
                _av = new SwiPrologTermVector(term.Arity);
                for (int index = 0; index < term.Arity; index++)
                {
                    if (0 == libswipl.PL_get_arg(index + 1, term.TermRef, _av[index].TermRef))
                    {
                        throw new SwiPrologException("PL_get_arg in PlQuery " + term.ToString());
                    }
                }
            }
#if _DEBUG
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print(ex.Message);
                Console.WriteLine(ex.Message);
            }
#endif
            finally
            {
                // NBT
            }
        }