Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  // ----------------------------------------------------------------------------
  // Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
  // 
  // This library is free software; you can redistribute it and/or
  // modify it under the terms of the GNU Lesser General Public
  // License as published by the Free Software Foundation; either
  // version 2.1 of the License, or (at your option) any later version.
  // 
  // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 // Lesser General Public License for more details.
 // 
 // You should have received a copy of the GNU Lesser General Public
 // License along with this library; if not, write to the Free Software
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 // 
 // To contact the authors:
 // http://www.inf.ufrgs.br/~bordini
 // http://www.das.ufsc.br/~jomi
 //
 //----------------------------------------------------------------------------
 
 package jason.asSyntax;
 
 
 import java.util.List;
This class represents an abstract literal (an Atom, Structure, Predicate, etc), it is mainly the interface of a literal. To create a new Literal, one of the following concrete classes may be used:
  • Atom -- the most simple literal, is composed by only a functor (no term, no annots);
  • Structure -- has functor and terms;
  • Pred -- has functor, terms, and annotations;
  • LiteralImpl -- Pred + negation.
The latter class supports all the operations of the Literal interface.

There are useful static methods in class ASSyntax to create Literals.

Author(s):
jomi
See also:
ASSyntax
Atom
Structure
Pred
LiteralImpl
Navassoc:
- type - PredicateIndicator
Opt:
nodefillcolor lightgoldenrodyellow
 
 public abstract class Literal extends DefaultTerm implements LogicalFormula {
 
     private static final long serialVersionUID = 1L;
     private static Logger logger = Logger.getLogger(Literal.class.getName());
     
     public static final boolean LPos   = true;
     public static final boolean LNeg   = false;
     public static final Literal LTrue  = new TrueLiteral();
     public static final Literal LFalse = new FalseLiteral();
 
     protected PredicateIndicator predicateIndicatorCache = null// to not compute it all the time (it is used many many times)
     
    
creates a new literal by parsing a string -- ASSyntax.parseLiteral or createLiteral are preferred.
 
     public static Literal parseLiteral(String sLiteral) {
         try {
             as2j parser = new as2j(new StringReader(sLiteral));
             return parser.literal();
         } catch (Exception e) {
             .log(.,"Error parsing literal " + sLiteral,e);
             return null;
         }
     }
     
     public Literal copy() {
         return (Literal)clone(); // should call the clone, that is overridden in subclasses
     }

    
returns the functor of this literal
 
     public abstract String getFunctor();
     
     @Override
    public boolean isLiteral() {
        return true;
    }
    
    
returns functor symbol "/" arity
        if ( == null) {
             = new PredicateIndicator(getFunctor(),getArity());
        }
        return ;
    }
    /* default implementation of some methods */

    
returns the number of terms of this literal
    public int getArity()         { return 0;  }
    
returns true if this literal has some term
    public boolean hasTerm()      { return false; } 
    
returns all terms of this literal
    public List<TermgetTerms()  { return .;   }
    
returns all terms of this literal as an array
    public Term[] getTermsArray() { return getTerms().toArray(.);  }
    
    private static final List<VarTermemptyListVar = new ArrayList<VarTerm>();
    
returns all singleton vars (that appears once) in this literal
    public List<VarTermgetSingletonVars() { return ; }

    
replaces all terms by unnamed variables (_).
    public void makeTermsAnnon()  {}
    
replaces all variables by unnamed variables (_).
    public Literal makeVarsAnnon()   { return this; }

    
replaces all variables of the term for unnamed variables (_).

Parameters:
un is the unifier that contains the map of replacements
    public Literal makeVarsAnnon(Unifier un) { return this; }

    
returns all annotations of the literal
    public ListTerm getAnnots()     { return null; }
    
returns true if there is some annotation t in the literal
    public boolean hasAnnot(Term t) { return false; }

    
returns true if the pred has at least one annot
    public boolean hasAnnot()       { return false; }
    
    
returns true if all this predicate annots are in p's annots
    public boolean hasSubsetAnnot(Literal p)            { return true; }
    
    
Returns true if all this predicate's annots are in p's annots using the unifier u. if p annots has a Tail, p annots's Tail will receive this predicate's annots, e.g.: this[a,b,c] = p[x,y,b|T] unifies and T is [a,c] (this will be a subset if p has a and c in its annots). if this annots has a tail, the Tail will receive all necessary term to be a subset, e.g.: this[b|T] = p[x,y,b] unifies and T is [x,y] (this will be a subset if T is [x,y].
    public boolean hasSubsetAnnot(Literal pUnifier u) { return true; }

    
removes all annotations
    public void    clearAnnots()    { }
    
    
returns all annots with the specified functor e.g.: from annots [t(a), t(b), source(tom)] and functor "t", it returns [t(a),t(b)] in case that there is no such an annot, it returns an empty list.
    public ListTerm getAnnots(String functor) { return new ListTermImpl(); }

    
returns the first annotation (literal) that has the functor
    public Literal getAnnot(String functor) { return null; }
    
    
returns the sources of this literal as a new list. e.g.: from annots [source(a), source(b)], it returns [a,b]
    public ListTerm getSources()    { return new ListTermImpl(); }
    
returns true if this literal has some source annotation
    public boolean hasSource()      { return false; }
    
returns true if this literal has a "source(agName)"
    public boolean hasSource(Term agName) { return false; }

    
returns this if this literal can be added in the belief base (Atoms, for instance, can not be)
    public boolean canBeAddedInBB() { return false; }
    
    
returns whether this literal is negated or not, use Literal.LNeg and Literal.LPos to compare the returned value
    public boolean negated()        { return false; }
    public boolean equalsAsStructure(Object p) { return false;  }
    
    
	/* Not implemented methods */
    // structure
    public void addTerm(Term t)              { .log(."addTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  }
    public void delTerm(int index)           { .log(."delTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  }
    
adds some terms and return this
    public Literal addTerms(Term ... ts )    { .log(."addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    
adds some terms and return this
    public Literal addTerms(List<Terml)    { .log(."addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    
returns the i-th term (first term is 0)
    public Term getTerm(int i)               { .log(."getTerm(i) is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    
set all terms of the literal and return this
    public Literal setTerms(List<Terml)    { .log(."setTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    public void setTerm(int iTerm t)       { .log(."setTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  }
    
    // pred
    public Literal setAnnots(ListTerm l)     { .log(."setAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    public boolean addAnnot(Term t)          { .log(."addAnnot("+t+") is not implemented in the class "+this.getClass().getSimpleName()+" of object "+thisnew Exception()); return false; }
    
    
adds some annots and return this
    public Literal addAnnots(Term ... terms) { .log(."addAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }

    
adds some annots and return this
    public Literal addAnnots(List<Terml)   { .log(."addAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    public boolean delAnnot(Term t)          { .log(."delAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  return false; }

    
removes all annots in this pred that are in the list l.

Returns:
true if some annot was removed.
    public boolean delAnnots(List<Terml)   { .log(."delAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }

    
"import" annots from another predicate p. p will be changed to contain only the annots actually imported (for Event), for example: p = b[a,b] this = b[b,c] after import, p = b[a] It is used to generate event <+b[a]>.

Returns:
true if some annot was imported.
    public boolean importAnnots(Literal p)   { .log(."importAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  return false; }

    
adds the annotation source(agName)
    public void addSource(Term agName)       { .log(."addSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  }
    
deletes one source(agName) annotation, return true if deleted
    public boolean delSource(Term agName)    { .log(."delSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  return false; }
    
deletes all source annotations
    public void delSources()                 { .log(."delSources is not implemented in the class "+this.getClass().getSimpleName(), new Exception());  }
    // literal    
    
changes the negation of the literal and return this
    public Literal setNegated(boolean b)     { .log(."setNegated is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
    
    
logicalConsequence checks whether one particular predicate is a logical consequence of the belief base. Returns an iterator for all unifiers that are logCons.
    public Iterator<UnifierlogicalConsequence(final Agent agfinal Unifier un) {
        final QueryProfiling   qProfiling;
        final QueryCacheSimple qCache;
        final long startTime;
        if (ag != null) {
            qCache     = ag.getQueryCache();
            qProfiling = ag.getQueryProfiling();
            if (qProfiling != null) {
                qProfiling.queryStared(this);
                startTime = System.nanoTime();
            } else {
                startTime = 0;
            }
        } else {
            qCache     = null;
            qProfiling = null;
            startTime  = 0;
        }
        
        final Iterator<Literalil   = ag.getBB().getCandidateBeliefs(thisun);
        if (il == null// no relevant bels
            return ..iterator();
        
        final AgArch            arch     = (ag != null && ag.getTS() != null ? ag.getTS().getUserAgArch() : null);
        final int               nbAnnots = (hasAnnot() && getAnnots().getTail() == null ? getAnnots().size() : 0); // if annots contains a tail (as in p[A|R]), do not backtrack on annots
        
        return new Iterator<Unifier>() {
            Unifier           current = null;
            Iterator<UnifierruleIt = null// current rule solutions iterator
            Literal           cloneAnnon = null// a copy of the literal with makeVarsAnnon
            Rule              rule// current rule
            boolean           needsUpdate = true;
            
            Iterator<List<Term>>  annotsOptions = null;
            Literal               belInBB = null;
            
            Literal kForChache = null;
            Iterator<UnifiercacheIt = null;
            //Literal cacheLit = null;
            //Unifier cacheUn = null;
            List<UnifiercacheResults = null
            
            public boolean hasNext() {
                if ()
                    get();
                
                if ( == null) { // end of query
                    if (qCache != null &&  != null
                        qCache.queryFinished();
                    if (qProfiling != null)
                        qProfiling.queryFinished(Literal.this, System.nanoTime() - startTime);
                }
                return  != null;
            }
            public Unifier next() {
                if ()
                    get();
                if ( != null)
                     = true;
                return ;
            }
            private void get() {
                 = false;
                     = null;
                if (arch != null && !arch.isRunning()) return;
                
                // try cache iterator
                if ( != null) {
                    while (.hasNext()) {
                        Literal ltmp = Literal.this.copy();
                        ltmp.apply.next() );
                        Unifier u = un.clone();
                        //System.out.println("   try "+ltmp);
                        if (u.unifiesNoUndo(Literal.thisltmp)) {
                            //System.out.println("           - ans from cache "+Literal.this+": "+u);
                             = u;
                            return;
                        }
                    }
                     = null;
                    return// do not try others after cache
                }
                
                // try annots iterator
                if ( != null) {
                    while (.hasNext()) {
                        Literal belToTry = .copy().setAnnots(null).addAnnots.next() );
                        Unifier u = un.clone();
                        if (u.unifiesNoUndo(Literal.thisbelToTry)) {
                             = u;
                            return;
                        }                    
                    }
                     = null;
                }
                
                // try rule iterator
                if ( != null) {
                    while (.hasNext()) {
                        // unifies the rule head with the result of rule evaluation
                        Unifier ruleUn = .next(); // evaluation result
                        Literal rhead  = .headClone();
                        rhead.apply(ruleUn);
                        useDerefVars(rheadruleUn); // replace vars by the bottom in the var clusters (e.g. X=_2; Y=_2, a(X,Y) ===> A(_2,_2))
                        rhead.makeVarsAnnon(); // to remove vars in head with original names
                        
                        Unifier unC = un.clone();
                        if (unC.unifiesNoUndo(Literal.thisrhead)) {
                             = unC;
                            /*if (kForChache != null) {
                                Unifier uforC = new Unifier();
                                if (uforC.unifiesNoUndo(kForChache, rhead))
                                    qCache.addAnswer(kForChache, uforC);
                                    cacheResults.add(uforC);
                            }*/
                            //System.out.println("   sol:"+unC+ " "+cacheResults);
                            if ( != null)
                                .add(unC);
                            return;
                        }
                    }
                     = null;
                }
                // try literal iterator
                while (il.hasNext()) {
                     = il.next(); // b is the relevant entry in BB
                    if (.isRule()) {
                         = (Rule);
                        
                        // create a copy of this literal, ground it and 
                        // make its vars anonymous, 
                        // it is used to define what will be the unifier used
                        // inside the rule.
                        if ( == null) {
                             = Literal.this.copy();
                            .apply(un);
                            .makeVarsAnnon();
                        }
                        
                        // try cache
                        if (ag != null && qCache != null) {
                        /*if (ag != null && qCache != null && kForChache == null) { // try cache only for the first rule (do not use cache for itself)
                            kForChache = cloneAnnon;
                            Pair<Literal,Iterator<Unifier>> pair = qCache.getCache(kForChache);
                            if (pair != null) {
                                cacheIt = pair.getSecond();
                                cacheLit = pair.getFirst();
                                //cacheUn = new Unifier();
                                //cacheUn.unifies(cacheLit, Literal.this);
                                //System.out.println("use un "+cacheUn+"/"+cacheLit+" for "+kForChache);
                                get();
                                return;
                            }*/
                             = Literal.this.copy();
                            .apply(un);
                            //System.out.println("try "+kForChache);
                             = qCache.getCache();
                            if ( != null) {
                                //System.out.println("use cache for "+kForChache);
                                get();
                                if ( != null// if it get a value
                                    return;
                            } 
                            //System.out.println("start collecting "+kForChache);
                             = new ArrayList<Unifier>();                                
                        }
                        Unifier ruleUn = new Unifier();
                        if (ruleUn.unifiesNoUndo()) { // the rule head unifies with the literal
                             = .getBody().logicalConsequence(ag,ruleUn);
                            get();
                            if ( != null// if it get a value
                                return;
                        }
                    } else { // not rule
                        if (nbAnnots > 0) { // try annots backtracking
                            if (.hasAnnot()) {
                                int nbAnnotsB = .getAnnots().size();
                                if (nbAnnotsB >= nbAnnots) {
                                     = .getAnnots().subSetsnbAnnots );
                                    get();
                                    if ( != null// if it get a value
                                        return;
                                }
                            }
                        } else { // it is an ordinary query on a belief
                            Unifier u = un.clone();
                            if (u.unifiesNoUndo(Literal.this)) {
                                 = u;
                                return;
                            }
                        }
                    }
                }
            }
            
            public void remove() {}
        };
    }   
    
    
    private void useDerefVars(Term pUnifier un) {
        if (p instanceof Literal) {
            Literal l = (Literal)p;
            for (int i=0; i<l.getArity(); i++) {
                Term t = l.getTerm(i);
                if (t.isVar()) {
                    l.setTerm(iun.deref( (VarTerm)t));
                } else {
                    useDerefVars(tun);                    
                }
            }
        }
    }
    
returns this literal as a list with three elements: [functor, list of terms, list of annots]
		ListTerm l = new ListTermImpl();
		ListTerm lt = new ListTermImpl();
		l.add(lt);
		if (hasAnnot()) {
		    l.add(getAnnots().cloneLT());
else {
		    l.add(new ListTermImpl());
		}
		return l;
	}

creates a literal from a list with three elements: [functor, list of terms, list of annots]
	public static Literal newFromListOfTerms(ListTerm ltthrows JasonException {
		try {
			Iterator<Termi = lt.iterator();
			Term tfunctor = i.next();
			boolean pos = .;
			if (tfunctor.isLiteral() && ((Literal)tfunctor).negated()) {
				pos = .;
			}
			if (tfunctor.isString()) {
			    tfunctor = ASSyntax.parseTerm( ((StringTerm)tfunctor).getString() );
			}
			Literal l = new LiteralImpl(pos,((Atom)tfunctor).getFunctor());
			if (i.hasNext()) {
			}
			if (i.hasNext()) {
			}
			return l;
catch (Exception e) {
			throw new JasonException("Error creating literal from "+lt);
		}
	}

    
Transforms this into a full literal (which implements all methods of Literal), if it is an Atom; otherwise returns 'this'
    public Literal forceFullLiteralImpl() {
        if (this.isAtom() && !(this instanceof LiteralImpl)) 
            return new LiteralImpl(this);
        else 
            return this;
    }
    @SuppressWarnings("serial")
    static final class TrueLiteral extends Atom {
    	public TrueLiteral() {
    		super("true");
		}
        
    	@Override
        public Iterator<UnifierlogicalConsequence(final Agent agfinal Unifier un) {
        	return LogExpr.createUnifIterator(un);            
        }
    }
    
    @SuppressWarnings("serial")
	static final class FalseLiteral extends Atom {
    	public FalseLiteral() {
    		super("false");
		}
    	
        @Override
        public Iterator<UnifierlogicalConsequence(final Agent agfinal Unifier un) {
        	return ..iterator();            
        }
    }
New to GrepCode? Check out our FAQ X