Esempio n. 1
0
        protected string ArgsToString(ITerm[] args)
        {
            StringBuilder sout = new StringBuilder();

            //try {
            //    if (ts.getSettings().logLevel() != Level.WARNING && args.length > 0) {
            //        sout = new StringBuilder();
            //    }
            //} catch (Exception e) {}

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].IsString())
                {
                    IStringTerm st = (IStringTerm)args[i];
                    sout.Append(st.GetString());
                }
                else
                {
                    ITerm t = args[i];
                    if (!t.IsVar())
                    {
                        sout.Append(t);
                    }
                    else
                    {
                        sout.Append(t + "<no-value>");
                    }
                }
            }
            return(sout.ToString());
        }
Esempio n. 2
0
        /// <inheritdoc />
        protected override void WriteStringTerm(IStringTerm term, TextWriter writer)
        {
            #region Contract
            if (term == null)
            {
                throw new ArgumentNullException(nameof(term));
            }
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            #endregion

            writer.Write('"');
            string escaped = StringEscaper.Escape(term.Value, new Dictionary <char, string>()
            {
                { '\n', "\\n" },                        // Line feed
                { '\r', "\\r" },                        // Carriage return
                { '\f', "\\f" },                        // Form feed
                { '\t', "\\t" },                        // Horizontal tab
                { '\v', "\\v" },                        // Vertical tab
                { '\b', "\\b" },                        // Backspace
                { '\\', "\\\\" },                       // Backslash
                { '\'', "\\'" },                        // Single quote
                { '"', "\\\"" },                        // Double quote
            });
            writer.Write(escaped);
            writer.Write('"');
            this.WriteAnnotations(term.Annotations, writer);
        }
Esempio n. 3
0
        public override object Execute(Reasoner ts, Unifier un, ITerm[] args)
        {
            IStringTerm time  = (IStringTerm)args[0];
            string      stime = time.GetString();

            //Parse time
            long deadline = -1;

            //If it start with now
            if (stime.StartsWith("now"))
            {
                //It is something like "now +3 minutes"
                stime = stime.Substring(3).Trim();
                //Get the amount of time
                if (stime.StartsWith("+"))
                {
                    stime = stime.Substring(1).Trim();
                    int pos = stime.IndexOf(" ");
                    if (pos > 0)
                    {
                        deadline = int.Parse(stime.Substring(0, pos));
                        //Get the time unit
                        stime = stime.Substring(pos).Trim();
                        if (stime.Equals("s") || stime.StartsWith("second"))
                        {
                            deadline *= 1000;
                        }
                        if (stime.Equals("m") || stime.StartsWith("minute"))
                        {
                            deadline *= 1000 * 60;
                        }
                        if (stime.Equals("h") || stime.StartsWith("hour"))
                        {
                            deadline *= 1000 * 60 * 60;
                        }
                        if (stime.Equals("d") || stime.StartsWith("day"))
                        {
                            deadline *= 1000 * 60 * 60 * 24;
                        }
                    }
                }
            }
            else
            {
                throw new JasonityException("The time parameter ('" + stime + "') of the internal action 'at' is not implemented!");
            }
            if (deadline == -1)
            {
                throw new JasonityException("The time parameter ('" + time + "') of the internal action 'at' did not parse correctly!");
            }

            Trigger te = Trigger.TryToGetTrigger(args[1]);

            Agent.GetExecutor().AddTask(new CheckDeadline(te, ts));

            //Agent.GetScheduler().Schedule(new CheckDeadline(te, ts), deadline, TimeUnit.MILLISECONDS);
            return(true);
        }
Esempio n. 4
0
 IStringTerm DeleteFromString(int index, int end, IStringTerm st)
 {
     try
     {
         string s = st.GetString();
         return(new StringTermImpl(s.Substring(0, index) + s.Substring(end)));
     }
     catch (Exception e)
     {
         return(st);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeATerm"/> class.
        /// </summary>
        /// <param name="factory">The factory that created this term.</param>
        /// <param name="name">The name.</param>
        /// <param name="annotations">The annotations of the term.</param>
        public TypeATerm(ITermFactory factory, IStringTerm name, IReadOnlyCollection <ITerm> annotations)
            : base(factory, annotations)
        {
            #region Contract
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            #endregion

            this.Name     = name;
            this.subterms = new SubtermCollection(this);
        }
Esempio n. 6
0
 IStringTerm DeleteFromString(IStringTerm st1, IStringTerm st2)
 {
     try
     {
         string s1 = st1.GetString();
         string s2 = st2.GetString();
         return(new StringTermImpl(s2.Replace(s1, " ")));
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         return(st1);
     }
 }
Esempio n. 7
0
        public override object Execute(Reasoner ts, Unifier un, ITerm[] args)
        {
            CheckArguments(args);
            ITerm l1 = args[0];

            if (l1.IsList())
            {
                IListTerm lt = l1 as IListTerm;
                return(lt.Count == 0);
            }
            else if (l1.IsString())
            {
                IStringTerm st = l1 as IStringTerm;
                return(st.GetString().Length == 0);
            }
            return(false);
        }
Esempio n. 8
0
        public void MakeVarsAnnon(Literal l, Unifier un)
        {
            try
            {
                for (int i = 0; i < l.GetArity(); i++)
                {
                    ITerm t = l.GetTerm(i);
                    if (t.IsString())
                    {
                        IStringTerm     st        = (IStringTerm)t;
                        MatchCollection matcher   = rx.Matches(st.GetString());
                        StringBuilder   sb        = new StringBuilder();
                        int             last      = 0;
                        var             userBlock = new List <string>();

                        foreach (Match item in matcher)
                        {
                            string sVar = item.Groups[0].Value;
                            sVar = sVar.Substring(2, sVar.Length - 1);
                            ITerm v = AsSyntax.AsSyntax.ParseTerm(sVar);
                            if (v.IsVar())
                            {
                                VarTerm to = ((Structure)l).VarToReplace(v, un);
                                //matcher.appendReplacement(sb, "#{" + to.ToString() + "}");
                                if (sVar.Trim().Length > 0)
                                {
                                    userBlock.Add(sVar);
                                    //No sabemos si esto está bien: el primer Append es para copiar el trozo
                                    //no matcheado y el segundo para el trozo que sí
                                    sb.Append(st.GetString().Substring(last, item.Index - last));
                                    sb.Append(t.IsString() ? ((IStringTerm)t).GetString() : t.ToString());
                                }
                                last = item.Index + item.Length;
                            }
                        }
                        //matcher.appendTail(sb);
                        sb.Append(st.GetString().Substring(last));
                        l.SetTerm(i, new StringTermImpl(sb.ToString()));
                    }
                }
            }
            catch (ParseException pe)
            {
                Debug.Log(pe.ToString());
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EntityATerm"/> class.
        /// </summary>
        /// <param name="factory">The factory that created this term.</param>
        /// <param name="name">The name.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="annotations">The annotations of the term.</param>
        public EntityATerm(ITermFactory factory, IStringTerm name, IListTerm <IPropertyTerm> properties, IReadOnlyCollection <ITerm> annotations)
            : base(factory, annotations)
        {
            #region Contract
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }
            #endregion

            this.Name       = name;
            this.Properties = properties;
            this.subterms   = new SubtermCollection(this);
        }
Esempio n. 10
0
        // Same as previous Add. If "before" is true, add at the beginning of the library.
        public Plan Add(IStringTerm stPlan, ITerm tSource, bool before)
        {
            string sPlan = stPlan.GetString();
            // Remove quotes
            StringBuilder sTemp = new StringBuilder();

            for (int c = 0; c < sPlan.Length; c++)
            {
                if (sPlan[c] != '\\')
                {
                    sTemp.Append(sPlan[c]);
                }
            }
            sPlan = sTemp.ToString();
            Plan p = AsSyntax.ParsePlan(sPlan); // ???

            return(Add(p, tSource, before));
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModuleATerm"/> class.
        /// </summary>
        /// <param name="factory">The factory that created this term.</param>
        /// <param name="name">The name.</param>
        /// <param name="definitions">The definitions.</param>
        /// <param name="annotations">The annotations of the term.</param>
        public ModuleATerm(ITermFactory factory, IStringTerm name, IListTerm <IEntityTerm> definitions, IReadOnlyCollection <ITerm> annotations)
            : base(factory, annotations)
        {
            #region Contract
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (definitions == null)
            {
                throw new ArgumentNullException(nameof(definitions));
            }
            #endregion

            this.Name        = name;
            this.Definitions = definitions;
            this.subterms    = new SubtermCollection(this);
        }
Esempio n. 12
0
		/// <inheritdoc />
		protected override void WriteStringTerm(IStringTerm term, TextWriter writer)
		{
			// CONTRACT: Inherited from TermTextWriter
			
			writer.Write('"');
			string escaped = StringEscaper.Escape(term.Value, new Dictionary<char, string>()
			{
				{ '\n', "\\n" },	// Line feed
				{ '\r', "\\r" },	// Carriage return
				{ '\f', "\\f" },	// Form feed
				{ '\t', "\\t" },	// Horizontal tab
				{ '\v', "\\v" },	// Vertical tab
				{ '\b', "\\b" },	// Backspace
				{ '\\', "\\\\" },	// Backslash
				{ '\'', "\\'" },	// Single quote
				{ '"',  "\\\"" },	// Double quote
			});
			writer.Write(escaped);
			writer.Write('"');
			this.WriteAnnotations(term.Annotations, writer);
		}
Esempio n. 13
0
        public override bool Equals(object t)
        {
            if (t == this)
            {
                return(true);
            }

            if (t != null && (t.GetType() == typeof(IStringTerm)))
            {
                IStringTerm st = (IStringTerm)t;
                if (value == null)
                {
                    return(st.GetString() == null);
                }
                else
                {
                    return(value.Equals(st.GetString()));
                }
            }
            return(false);
        }
Esempio n. 14
0
        public override object Execute(Reasoner reasoner, Unifier un, ITerm[] args)
        {
            CheckArguments(args);
            ITerm l1 = args[0];
            ITerm l2 = args[1];

            INumberTerm size = null;

            if (l1.IsList())
            {
                IListTerm lt = (IListTerm)l1;
                size = new NumberTermImpl(lt.Size());
            }
            else if (l1.IsString())
            {
                IStringTerm st = (IStringTerm)l1;
                size = new NumberTermImpl(st.GetString().Length);
            }
            if (size != null)
            {
                return(un.Unifies(l2, size));
            }
            return(false);
        }
Esempio n. 15
0
 /// <summary>
 /// Writes a string term to the specified writer.
 /// </summary>
 /// <param name="term">The term to write.</param>
 /// <param name="writer">The text writer to write to.</param>
 protected abstract void WriteStringTerm(IStringTerm term, TextWriter writer);
Esempio n. 16
0
 // Adds a new plan written as a string. Source is usually "self" or the agent who sent this plan.
 // New plans are added at the end of the library.
 public Plan Add(IStringTerm stPlan, ITerm tSource) => Add(stPlan, tSource, false);
Esempio n. 17
0
			protected override void WriteStringTerm(IStringTerm term, TextWriter writer)
			{
				Contract.Requires(term != null);
				Contract.Requires(writer != null);
			}
Esempio n. 18
0
		/// <summary>
		/// Writes a string term to the specified writer.
		/// </summary>
		/// <param name="term">The term to write.</param>
		/// <param name="writer">The text writer to write to.</param>
		protected abstract void WriteStringTerm(IStringTerm term, TextWriter writer);
Esempio n. 19
0
			public void VisitString(IStringTerm term)
			{
				Contract.Requires<ArgumentNullException>(term != null);
			}
Esempio n. 20
0
        /*
         * @Override
         * public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
         *  checkArguments(args);
         *  StringBuffer sb = new StringBuffer();
         *  for (Term term : args) {
         *      if (!term.isString()) {
         *          continue;
         *      }
         *      StringTerm st = (StringTerm) term;
         *      Matcher matcher = regex.matcher(st.getString());
         *
         *      while (matcher.find()) {
         *
         *          //System.out.println("I found the text \""+matcher.group()+ "\"starting at index "+matcher.start()+ " and ending at index "+matcher.end());
         *
         *          String sVar = matcher.group();
         *          sVar = sVar.substring(2, sVar.length() - 1); //Quita los dos primeros caracteres: # y \, creo que es lo primero que aparece en las variables; y también quita el último: \
         *          try {
         *              Term t = null;
         *              if (sVar.startsWith("_") && sVar.length() > 1) // deals with unnamed vars, where we cannot use parseTerm
         *                  t = new UnnamedVar( Integer.valueOf( sVar.substring(1))); //Le quita la _ al nombre de la variable anónima
         *              else
         *                  t = ASSyntax.parseTerm(sVar); //si no ya si que llama al término
         *
         *              //We use t.apply to evaluate any logical or arithmetic expression in Jason
         *              t = t.capply(un);
         *              matcher.appendReplacement(sb, t.isString() ? ((StringTerm)t).getString() : t.toString());
         *          } catch (ParseException pe) {
         *              // TODO: handle exception
         *              // TODO: Decide whether or not we should ignore the exception and print the call instead
         *              // Right now, if I get a parse error from ASSyntax, I just print the original escaped
         *              // sequence, so a user can see that his/her expression was problematic
         *              matcher.appendReplacement(sb, "#{"+sVar+"}");
         *          }
         *
         *      }
         *      matcher.appendTail(sb);
         *  }
         *
         *  if (args[args.length - 1].isVar()) {
         *      //Guardar el mensaje todo ello unificado en una sola variable, para depurar
         *      StringTerm stRes = new StringTermImpl(sb.toString());
         *      return un.unifies(stRes, args[args.length - 1]);
         *  } else {
         *      //Si no hay una variable, lo que quiero es sacar por pantalla todo el mensaje completo
         *      ts.getLogger().info(sb.toString()); //Aquí es por donde se saca por la consola lo que el progrmamador haya querido en su asl
         *      return true;
         *  }
         * }
         */

        public override object Execute(Reasoner r, Unifier un, ITerm[] args)
        {
            CheckArguments(args);
            StringBuilder sb = new StringBuilder();

            foreach (ITerm term in args)
            {
                if (!term.IsString())
                {
                    continue;
                }
                IStringTerm     st        = (IStringTerm)term;
                MatchCollection matcher   = rx.Matches(st.GetString());
                int             last      = 0;
                var             userBlock = new List <string>();

                foreach (Match item in matcher)
                {
                    //matcher.groups
                    string sVar = item.Groups[0].Value;

                    sVar = sVar.Substring(2, sVar.Length - 1);
                    try
                    {
                        ITerm t = null;
                        if (sVar.StartsWith("_") && sVar.Length > 1)
                        {
                            t = new UnnamedVar(int.Parse(sVar.Substring(1)));
                        }
                        else
                        {
                            t = AsSyntax.AsSyntax.ParseTerm(sVar);
                        }
                        t = t.CApply(un);
                        //Hacer Regex.Replace(sb, t.IsString() ?....) serría una opción para hacerlo más compacto pero no sabemos
                        //matcher.appendReplacement(sb, t.IsString() ? ((IStringTerm)t).GetString() : t.ToString());

                        if (sVar.Trim().Length > 0)
                        {
                            userBlock.Add(sVar);
                            //No sabemos si esto está bien: el primer Append es para copiar el trozo
                            //no matcheado y el segundo para el trozo que sí
                            sb.Append(st.GetString().Substring(last, item.Index - last));
                            sb.Append(t.IsString() ? ((IStringTerm)t).GetString() : t.ToString());
                        }
                        last = item.Index + item.Length;
                    }
                    catch (ParseException pe)
                    {
                        //matcher.appendReplacement(sb, "#{" + sVar + "}");
                        //Creemos que esto es para añadir el trocito que falta (va a estar mal seguro)
                        sb.Append("#{" + sVar + "}");
                    }
                }
                //matcher.appendTail(sb);
                sb.Append(st.GetString().Substring(last));//Aquí hay que añadir lo que falta de la cadena original que no matchea
            }

            if (args[args.Length - 1].IsVar())
            {
                IStringTerm stRes = new StringTermImpl(sb.ToString());
                return(un.Unifies(stRes, args[args.Length - 1]));
            }
            else
            {
                //r.GetLogger().Info(sb.ToString());
                return(true);
            }
        }