aboutsummaryrefslogtreecommitdiff
path: root/src/builtin/PRED_atom_codes_2.java
blob: 9d1e9ec6316c400e5e62848f92e236e9fe3b2c2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package jp.ac.kobe_u.cs.prolog.builtin;
import  jp.ac.kobe_u.cs.prolog.lang.*;
/**
 * <code>atom_codes/2</code><br>
 * @author Mutsunori Banbara (banbara@kobe-u.ac.jp)
 * @author Naoyuki Tamura (tamura@kobe-u.ac.jp)
 * @version 1.1
 */
public class PRED_atom_codes_2 extends Predicate.P2 {
    private static final SymbolTerm Nil = SymbolTerm.makeSymbol("[]");

    public PRED_atom_codes_2(Term a1, Term a2, Operation cont) {
	arg1 = a1;
	arg2 = a2;
	this.cont = cont;
    }

    public Operation exec(Prolog engine) {
        engine.setB0();
	Term a1, a2;
	a1 = arg1;
	a2 = arg2;

	a1 = a1.dereference();
	a2 = a2.dereference();
	if (a1.isVariable()) { // atom_codes(-Atom, +CharCodeList)
	    StringBuffer sb = new StringBuffer();
	    Term x = a2;
	    while(! x.isNil()) {
		if (x.isVariable())
		    throw new PInstantiationException(this, 2);
		if (! x.isList())
		    throw new IllegalTypeException(this, 2, "list", a2);
		Term car = ((ListTerm)x).car().dereference();
		if (car.isVariable())
		    throw new PInstantiationException(this, 2);
		if (! car.isInteger()) 
		    throw new RepresentationException(this, 2, "character_code");
		// car is an integer
		int i = ((IntegerTerm)car).intValue();
		if (! Character.isDefined((char)i))
		    throw new RepresentationException(this, 2, "character_code");
		sb.append((char)i);
		x = ((ListTerm)x).cdr().dereference();
	    }
	    if (! a1.unify(SymbolTerm.makeSymbol(sb.toString()), engine.trail))
		return engine.fail();
	    return cont;
	} else { // atom_codes(+Atom, ?CharCodeList)
	    if (! a1.isSymbol())
		throw new IllegalTypeException(this, 1, "atom", a1);
	    char[] chars = ((SymbolTerm)a1).name().toCharArray();
	    Term x = Nil;
	    for (int i=chars.length; i>0; i--) {
		x = new ListTerm(new IntegerTerm((int)chars[i-1]), x);
	    }
	    if(! a2.unify(x, engine.trail)) 
		return engine.fail();
	    return cont;
	}
    }
}