forked from mit-dig/air-reasoner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
term.py
executable file
·1925 lines (1612 loc) · 65.3 KB
/
term.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python
"""
$Id: term.py,v 1.75 2007/06/26 15:30:53 syosi Exp $
term
This module defines objects correspodning to the basic terms in the
RDF and N3 langauges: Symbols, Literals and Lists. (The N3 language
goes on to include formuale, which are defined elsewhere)
The code in this module deals with the represnetation of these terms
and in debug form (__repr__)
Interning of URIs and strings for storage in SWAP store.
It also defines the utility Namespace module which makes using terms
in practice both more convenient maybe even more efficient than
carrying full URIs around.
Includes:
- template classes for builtins
"""
from __future__ import generators # for yield
import string, sys, types
from set_importer import Set, ImmutableSet
import uripath # DanC's tested and correct one
import hashlib, binascii # for building md5 URIs
from uripath import refTo
from RDFSink import runNamespace
from local_decimal import Decimal # for xsd:decimal
LITERAL_URI_prefix = "data:application/rdf+n3-literal;"
from RDFSink import List_NS
from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4
from RDFSink import FORMULA, LITERAL, LITERAL_LANG, LITERAL_DT, ANONYMOUS, \
SYMBOL, RDF_type_URI
from RDFSink import Logic_NS
from RDFSink import N3_first, N3_rest, N3_nil
from OrderedSequence import merge, intersection, minus
import diag
from diag import progress
from weakref import WeakValueDictionary
import sys
if sys.hexversion < 0x02030000:
raise RuntimeError("Sorry, this software requires python2.3 or newer.")
######################################## Storage URI Handling
#
# In general a Symbol has a URI which may or may not have a "#" and
# fragment identifier. This code keeps track of URIs which are the
# same up to the hash, so as to make it easy to discover for example
# whether a term is a local identifier within a document which we know
# about. This is relevant to the URI-spec related processing rather
# than the RDF-spec related processing.
#
# than just a URI. It has subclasses of Symbol and Fragment.
#
# (libwww equivalent HTParentAnchor and HTChildAnchor IIRC)
#
# Every resource has a symbol table of fragments.
# A resource may (later) have a connection to a bunch of parsed stuff.
#
# We are nesting symbols two deep let's make a symbol table for each resource
#
# The statement store lists are to reduce the search time for triples
# in some cases. Of course, indexes would be faster. But we can
# figure out what to optimize later. The target for now is being able
# to find synonyms and so translate documents.
class Env(dict):
"""An env is an immutable dict
You can hash it (if you want to)
"""
__slots__ = ['_hashval', '__weakref__', 'id']
def __init__(self, other=None, keywords={}):
self.id = None
if other is None:
dict.__init__(self)
else:
keywords.update(other.iteritems())
dict.__init__(self, keywords)
self.id = self
for k, (a,b) in self.iteritems():
if isinstance(a, tuple):
raise RuntimeError("%s : (%s, %s)" % (k, a, b))
def copy(self):
return self ## I'm immutable!
def update(self, d2):
k = self.__class__(self, d2)
raise RuntimeError("I'm immutable!, %s" % k)
def update2(self, d2):
k = self.__class__(self, d2)
return k
def asDict(self):
retVal = {}
for k in self:
retVal[k] = self[k]
return retVal
def newBinding(self, var, val):
assert isinstance(val, tuple) and len(val) == 2, val
retVal = Env(self, {var: val})
retVal.id = self.id
return retVal
bind = newBinding
def __setitem__(self, item, val):
if self.id is not None:
raise TypeError
dict.__setitem__(self, item, val)
def __getitem__(self, item):
return dict.__getitem__(self, item)[0]
def get(self, item, default=None):
return dict.get(self, item, (default,))[0]
def dereference(self, var):
try:
hash(var)
except TypeError:
return var
return dict.get(self, var, (var, self.id))
def flatten(self, other):
"""Pull all of the bindings of other into a copy of self
"""
# from backward import progress
# progress(lambda : 'Env.flatten(%s,%s)' % (self, other))
retVal = dict(other)
for key, (val, source) in self.items():
if key in other:
if source == dict.__getitem__(other, key)[1] and val != other[key]:
raise ValueError(self[key], other[key])
if source is other.id:
retVal[key] = (other.substitution(val, self), self.id)
else:
retVal[key] = (val, source)
# Unclear why keywords needs to be explicitly {} here, but
# sometimes it's already set???
retVal = self.__class__(retVal, keywords={})
retVal.id = self.id
# progress(lambda : '... returns %s' % retVal)
return retVal
def substitution(self, node, *otherEnvs):
if self not in otherEnvs:
envs = (self,) + otherEnvs
if node in self:
k, s = self.dereference(node)
for env in envs:
if s is env.id:
return env.substitution(k, *envs)
elif isinstance(node, list):
return [self.substitution(x, otherEnvs) for x in node]
if isinstance(node, tuple):
return tuple([self.substitution(x, otherEnvs) for x in node])
if isinstance(node, (formula.StoredStatement, term.Term)):
return node.substitution(self) ## Wrong!
return node
def canBind(self, var, val):
if var in self:
return self[var] == val
return True
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
def __hash__(self):
try:
return self._hashval
except AttributeError:
self._hashval = hash(ImmutableSet(self.items()))
return self._hashval
def pickEnv(choice, *envs):
for env in envs:
if choice is env.id:
return env
return [] ## Not here.
class Term(object):
"""The Term object represents an RDF term.
It is interned for speed of processing by the store.
Every term has a pointer back to its store.
"""
def __init__(self, store):
self.store = store
def __repr__(self):
"""This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
"""
s = self.uriref()
p = string.rfind(s, "#")
if p < 0: # No hash, use slash
p = s.rfind("/", 0, len(s) - 2)
# Allow "/" namespaces as a second best, not a trailing one
if (p >= 0 and s[p+1:].find(".") < 0 ):
# Can't use prefix if localname includes "."
prefix = self.store.prefixes.get(s[:p+1], None) # @@ #CONVENTION
if prefix != None:
return (prefix + ":" + s[p+1:]).encode('unicode_escape')
if s.endswith("#_formula"):
return "`" + s[-22:-9] + "`" # Hack - debug notation for formula
if p >= 0: return s[p+1:].encode('unicode_escape')
return s.encode('unicode_escape')
def debugString(self, already=[]):
return `self` # unless more eleborate in superclass
def representation(self, base=None):
"""The string representing this in N3."""
return "<" + self.uriref(base) + ">"
def generated(self):
"""Boolean: Is this thing a genid - is its name arbitrary? """
return 0 # unless overridden
def compareAnyTerm(self, other):
"""Compare two langauge items
This is a cannoncial ordering in that is designed to allow the
same graph always to be printed in the same order. This makes
the regression tests possible. The literals are deemed
smaller than symbols, which are smaller than formulae. This
puts the rules at the bottom of a file where they tend to take
a lot of space anyway. Formulae have to be compared as a
function of their sorted contents.
@@ Anonymous nodes have to, within a given Formula, be
compared as a function of the sorted information about them in
that context. This is not done yet
"""
if self is other: return 0
diff = cmp(self.classOrder(), other.classOrder())
if diff != 0: return diff
return self.compareTerm(other)
def asPair(self):
"""Representation in an earlier format, being phased out 2002/08.
The first part of the pair is a constant number represnting
the type see RDFSink.py. the second is the value -- uri for
symbols, string for literals"""
return (SYMBOL, self.uriref())
def substitution(self, bindings, why=None, cannon=False):
"Return this or a version of me with subsitution made."
return bindings.get(self, self)
def substituteEquals(self, bindings, newRedirections):
"Return this or a version of me with substitution made."
return bindings.get(self, self)
def occurringIn(self, vars):
if self in vars:
return Set([self])
return Set()
def value(self):
"As a python value - by default, none exists, use self"
return self
def doesNodeAppear(self, symbol):
"""Does that node appear within this one
This non-overloaded function will simply return if I'm equal
to him
"""
return self == symbol
def unify(self, other, env1=Env(), env2=Env(), vars=Set(),
universals=Set(), existentials=Set(), n1Source=32, n2Source=32):
return unify(self, other, env1, env2, vars, universals, existentials,
n1Source, n2Source)
## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}):
## """Unify this which may contain variables with the other,
## which may contain existentials but not variables.
##
## vars are variables we want a binding for if matched
## existentials are things we don't need a binding returned for
## bindings are those bindings already made in this unification
##
## Return [] if impossible.
## return [({}, reason] if no new bindings
## Return [( {var1: val1, var2: val2,...}, reason), ...] if match
## """
## assert type(bindings) is types.DictType
## if diag.chatty_flag > 97:
## progress("Unifying symbol %s with %s vars=%s, so far=%s"%
## (self, other,vars, bindings))
## s = bindings.get(self, self)
## if s is other:
## return [ ({}, None)]
## if s in vars|existentials:
## if diag.chatty_flag > 80:
## progress("Unifying var or exi MATCHED %s to %s"%(s, other))
## return [ ({s: other}, None) ]
## if diag.chatty_flag > 99:
## progress("Failed Unifying symbol %s with %s vars=%s, so far=%s"%
## (self, other, vars, bindings))
## return []
def unifySecondary(self, other, env1, env2, vars, universals, existentials,
n1Source=55, n2Source=55):
if self is other:
yield (env1, env2)
def freeVariables(self):
return Set()
class ErrorFlag(TypeError, Term):
__init__ = TypeError.__init__
__repr__ = TypeError.__str__
__str__ = TypeError.__str__
# uriref = lambda s: ':'
value = lambda s: s
def classOrder(self):
return 99
class Node(Term):
"""A node in the graph.
"""
pass
class LabelledNode(Node):
"The labelled node is one which has a URI."
def compareTerm(self, other):
"""Assume is also a LabelledNode - see function compareTerm in
formula.py"""
_type = RDF_type_URI
s = self.uriref()
if self is self.store.type:
return -1
o = other.uriref()
if other is self.store.type:
return 1
retVal = cmp(s, o)
if retVal:
return retVal
progress( "Error with '%s' being the same as '%s'" %(s,o))
raise RuntimeError(
"""Internal error: URIref strings should not match if not same object,
comparing %s and %s""" % (s, o))
def classOrder(self):
return 6
class Symbol(LabelledNode):
"""A Term which has no fragment.
"""
def __init__(self, uri, store):
Term.__init__(self, store)
assert string.find(uri, "#") < 0, "no fragments allowed: %s" % uri
assert ':' in uri, "must be absolute: %s" % uri
self.uri = uri
self.fragments = WeakValueDictionary()
def uriref2(self, base):
assert ':' in base, "base must be absolute: %s" % base
return refTo(base, self.uri)
def uriref(self):
# assert ':' in self.uri, "oops! must be absolute: %s" % self.uri
return self.uri
def internFrag(self, fragid, thetype): # type was only Fragment before
f = self.fragments.get(fragid, None)
if f != None:
if not isinstance(f, thetype):
raise RuntimeError(
"Oops.. %s exists already but not with type %s"
% (f, thetype))
return f # (Could check that types match just to be sure)
f = thetype(self, fragid)
self.fragments[fragid] = f
return f
def __getitem__(self, lname):
"""get the lname Symbol in this namespace.
lname -- an XML name (limited to URI characters)
"""
if lname.startswith("__"): # python internal
raise AttributeError, lname
return self.internFrag(lname, Fragment)
def dereference(self, mode="", workingContext=None):
"""dereference an identifier, finding the semantics of its schema if
any.
Returns None if it cannot be retreived.
"""
if hasattr(self, "_semantics"):
F = self._semantics
else:
inputURI = self.uriref()
if diag.chatty_flag > 20: progress("Web: Looking up %s" % self)
if "E" not in mode: F = self.store.load(inputURI)
else:
try:
F = self.store.load(inputURI)
except:
#except (IOError, SyntaxError, DocumentAccessError,
# xml.sax._exceptions.SAXParseException):
F = None
if F != None:
if "m" in mode:
workingContext.reopen()
if diag.chatty_flag > 45:
progress("Web: dereferenced %s added to %s"
% (self, workingContext))
workingContext.store.copyFormula(F, workingContext)
if "x" in mode: # capture experience
workingContext.add(r, self.store.semantics, F)
if not hasattr(self, "_semantics"):
setattr(self, "_semantics", F)
if diag.chatty_flag > 25:
progress("Web: Dereferencing %s gave %s" %(self, F))
return F
class Fragment(LabelledNode):
"""A Term which DOES have a fragment id in its URI.
"""
def __init__(self, resource, fragid):
Term.__init__(self, resource.store)
self.resource = resource
self.fragid = fragid
def compareTerm(self, other):
if not isinstance(other, Fragment):
return LabelledNode.compareTerm(self, other)
if self is self.resource.store.type:
return -1
if other is self.resource.store.type:
return 1
if self.resource is other.resource:
return cmp(self.fragid, other.fragid)
return self.resource.compareTerm(other.resource)
def uriref(self):
return self.resource.uri + "#" + self.fragid
def uriref2(self, base):
return self.resource.uriref2(base) + "#" + self.fragid
def representation(self, base=None):
""" Optimize output if prefixes available
"""
return "<" + self.uriref2(base) + ">"
def generated(self):
""" A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
"""
return 0 # Use class Anonymous for generated IDs
def dereference(self, mode="", workingContext=None):
"""dereference an identifier, finding the semantics of its schema if
any
Returns None if it cannot be retreived.
"""
return self.resource.dereference(mode, workingContext)
nextId = 0
class AnonymousNode(Node):
"""Has no real URI except when needed for output. Goal is to
eliminate use of this URI in the code. The URI is however useful
as a diagnostic, so we carry it when it is given. It is NOT
checked for uniqueness etc. This is a superclass of many things,
including AnonymousExistential, which has a scope."""
def __init__(self, store, uri=None):
global nextId
try:
if uri: assert isinstance(uri, tuple(types.StringTypes))
except:
print uri
print type(uri)
print '---------=============------------'
raise
Term.__init__(self, store)
self._diagnosticURI = uri
nextId += 1
self.serial = nextId
def compareTerm(self, other):
"Assume is also a Formula - see function compareTerm below"
if hasattr(self, 'uri'):
selfSerial = self.uri
else:
selfSerial = self.serial
if hasattr(other, 'uri'):
otherSerial = other.uri
else:
otherSerial = other.serial
retVal = cmp(selfSerial, otherSerial)
if retVal:
return retVal
return cmp(self.serial, other.serial)
def classOrder(self):
"""Anonymous nodes are higher than symbols as the = smushing tries to
minimize the order rank of the node which it adopts as the
representative node of an equivalence class."""
return 9
def uriref(self):
if self._diagnosticURI: return self._diagnosticURI
return runNamespace() + "_g" + `self.serial`
# return runNamespace() + "_b" + `id(self)`
def generated(self):
return 1
def asPair(self):
return (ANONYMOUS, self.uriref())
def freeVariables(self):
return Set([self])
class Universal(Term):
__repr__ = object.__repr__
class Existential(Term):
__repr__ = object.__repr__
class SkolemFunction(Existential):
pass
class AnonymousVariable(AnonymousNode):
"""An anonymous node which is existentially quantified in a given
context. Also known as a Blank Node, or "bnode" in RDF
parlance."""
def __init__(self, scope, uri=None):
AnonymousNode.__init__(self, scope.store, uri)
class AnonymousExistential(AnonymousVariable, Existential):
"""An anonymous node which is existentially quantified in a given
context. Also known as a Blank Node, or "bnode" in RDF
parlance."""
__repr__= AnonymousVariable.__repr__
class AnonymousUniversal(AnonymousVariable, Universal):
"""Nodes which are introduced as universally quantified variables with
no quotable URI"""
def __init__(self, scope, uri=None):
if isinstance(uri, Term):
if isinstance(uri, AnonymousUniversal):
uri = uri.uri
elif isinstance(uri, AnonymousNode):
uri = None
elif isinstance(uri, LabelledNode):
uri = uri.uriref()
self.scope = scope
self.uri = uri
AnonymousVariable.__init__(self, scope, uri)
scope.declareUniversal(self, key=self.__class__)
def asPair(self):
if not self.uri:
return AnonymousVariable.asPair(self)
return (SYMBOL, self.uriref())
__repr__= AnonymousVariable.__repr__
## def __repr__(self):
## return str(abs(id(self)))
##########################################################################
#
# L I S T S
#
# Lists are interned, so python object comparison works for
# log:equalTo. For this reason, do NOT use a regular init, always use
# rest.prepend(first) to generate a new list form an old, or
# nil.prepend(first) for a singleton, or nil.newList(somePythonList)
#
# This lists can only hold hashable objects - but we only use hashable
# objects in statements.
#
# These don't have much to be said for them, compared with python
# lists, except that (a) they are hashable, and (b) if you do your
# procesing using first and rest a lot, you don't generate n(n+1)/2
# list elements when traversing (which you probably don't anyway using
# slices)
#
# Many different implementations are of course possible.
#
_nextList = 0
class CompoundTerm(Term):
"""A compound term has occurrences of terms within it.
Examples: List, Formula"""
pass
class N3Set(ImmutableSet, CompoundTerm): #,
"""There can only be one of every N3Set.
"""
res = {}
def __init__(self, stuff=[]):
"""something"""
ImmutableSet.__init__(self, stuff)
def __new__(cls, stuff=[]):
new_set = ImmutableSet.__new__(cls, stuff)
new_set.__init__(stuff)
if new_set in cls.res:
return cls.res[new_set]
cls.res[new_set] = new_set
return new_set
## def __setattr__(self, attr, value):
## print "%s=%s" % (`attr`, `value`)
## ImmutableSet.__setattr__(self, attr, value)
def uriref(self):
raise NotImplementedError
def substitution(self, bindings, why=None, cannon=False):
"Return this or a version of me with variable substitution made"
if self.occurringIn(bindings.keys()) == Set():
return self # phew!
return self.__class__([x.substitution(bindings, why=why, cannon=cannon) for x in self])
def substituteEquals(self, bindings, newBindings):
"Return this or a version of me with substitution of equals made"
if diag.chatty_flag > 100:
progress("SubstituteEquals list %s with %s" % (self, bindings))
if self.occurringIn(bindings.keys()) == Set():
return self # phew!
new = self.__class__([x.substitution(bindings, why=why) for x in self])
newBindings[self] = new
return new
def occurringIn(self, vars):
union = Set.union
return reduce(union, [x.occurringIn(vars) for x in self], Set())
def asSequence(self):
return self
def classOrder(self):
return 10
def unifySecondary(self, other, env1, env2, vars, universals, existentials,
n1Source=55, n2Source=55):
return unifySet(self, other, env1, env2, vars, universals,
existentials, n1Source, n2Source)
def compareTerm(self, other):
"""This is annoying.
"""
def my_max(the_set):
Max = None
for a in the_set:
if Max == None or a.compareAnyTerm(Max) > 0:
Max = a
return Max
s1 = self - other
s2 = other - self
max1 = my_max(s1)
max2 = my_max(s2)
if max1 is max2: return 0
if max1 is None: return -1
if max2 is None: return 1
return max1.compareAnyTerm(max2)
def freeVariables(self):
union = Set.union
return reduce(union, [x.freeVariables() for x in self], Set())
class List(CompoundTerm):
def __init__(self, store, first, rest): # Do not use directly
global _nextList
Term.__init__(self, store)
self.first = first
self.rest = rest
self._prec = {}
self._id = _nextList
_nextList = _nextList + 1
def uriref(self):
return runNamespace() + "li"+ `self._id`
def prepend(self, first):
x = self._prec.get(first, None)
if x != None: return x
x = NonEmptyList(self.store, first, self)
self._prec[first] = x
return x
def __iter__(self):
"""The internal method which allows one to iterate over the statements
as though a formula were a sequence.
"""
x = self
while x is not self.store.nil:
yield x.first
x = x.rest
def __len__(self):
"""The internal method which allows one to count the statements
as though a formula were a sequence.
"""
x = self
i = 0
while x is not self.store.nil:
i = i + 1
x = x.rest
return i
def value(self):
res = []
for x in self:
if isinstance(x, types.StringTypes):
res.append(x)
else:
res.append(x.value())
return res
def substitution(self, bindings, why=None, cannon=False):
"Return this or a version of me with variable substitution made"
if self.occurringIn(bindings.keys()) == Set():
return self # phew!
s = self.asSequence()
s.reverse()
tail = self.store.nil
for x in s:
tail = tail.prepend(x.substitution(bindings, why=why, cannon=cannon))
if diag.chatty_flag > 90:
progress("Substition of variables %s in list %s" % (bindings, self))
progress("...yields NEW %s = %s" % (tail, tail.value()))
return tail
def substituteEquals(self, bindings, newBindings):
"Return this or a version of me with substitution of equals made"
if diag.chatty_flag > 100:
progress("SubstituteEquals list %s with %s" % (self, bindings))
if self.occurringIn(bindings.keys()) == Set():
return self # phew!
s = self.asSequence()
s.reverse()
tail = self.store.nil
for x in s:
tail = tail.prepend(x.substituteEquals(bindings, newBindings))
newBindings[self] = tail # record a new equality
self.generated = lambda : True
if diag.chatty_flag > 90:
progress("SubstitueEquals list CHANGED %s -> %s" % (self, tail))
return tail
def occurringIn(self, vars):
"Which variables in the list occur in this list?"
set = Set()
x = self
while not isinstance(x, EmptyList):
y = x.first
x = x.rest
import types
set = set | y.occurringIn(vars)
if self in vars:
set.add(self)
return set
def asSequence(self):
"Convert to a python sequence - NOT recursive"
res = []
x = self
while x is not self.store.nil:
res.append(x.first)
x = x.rest
return res
def doesNodeAppear(self, symbol):
"""Does that particular node appear anywhere in this list
This function is necessarily recursive, and is useful for the
pretty printer. It will also be useful for the flattener, when
we write it.
"""
for elt in self:
val = 0
if isinstance(elt, CompoundTerm):
val = val or elt.doesNodeAppear(symbol)
elif elt == symbol:
val = 1
else:
pass
if val == 1:
print 'I won!'
return 1
return 0
def freeVariables(self):
union = Set.union
return reduce(union, [x.freeVariables() for x in self], Set())
class NonEmptyList(List):
def classOrder(self):
return 3
def compareTerm(self, other):
"""Assume is also a NonEmptyList - see function compareTerm in
formula.py
"""
s = self
o = other
while 1:
if isinstance(o, EmptyList): return -1
if isinstance(s, EmptyList): return 1
diff = s.first.compareAnyTerm(o.first)
if diff != 0: return diff
s = s.rest
o = o.rest
## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}):
## """See Term.unify()"""
## if diag.chatty_flag > 90:
## progress("Unifying list %s with %s vars=%s, so far=%s"%
## (self.value(), other.value(),vars, bindings))
## if not isinstance(other, NonEmptyList): return []
## if other is self: return [ ({}, None)]
##
## # Using the sequence-like properties of lists:
## return unifySequence(self, other, vars, existentials, bindings)
def unifySecondary(self, other, env1, env2, vars, universals, existentials,
n1Source=55, n2Source=55):
return unifySequence(self, other, env1, env2, vars, universals,
existentials, n1Source, n2Source)
def debugString(self, already=[]):
s = `self`+" is ("
for i in self:
s = s + i.debugString(already) + " "
return s + ")"
# def __repr__(self):
# return "(" + `self.first` + "...)"
def __getitem__(self, i):
p = self
while 1:
if i == 0: return p.first
p = p.rest
if not isinstance(p, NonEmptyList):
raise ValueError("Index %i exceeds size of list %s"
% (i, `self`))
i = i - 1
class EmptyList(List):
def classOrder(self):
return 2
def value(self):
return []
def uriref(self):
return List_NS + "nil"
def substitution(self, bindings, why=None, cannon=False):
"Return this or a version of me with substitution made"
return self
def substituteEquals(self, bindings, newBindings):
"Return this or a version of me with substitution of equals made"
return self
def __repr__(self):
return "()"
def newList(self, value):
x = self
l = len(value)
if l == 0:
return x
try:
value[0]
except TypeError:
for a in value:
x = x.prepend(a)
else:
while l > 0:
l = l - 1
x = x.prepend(value[l])
return x
## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}):
## """Unify the substitution of this using bindings found so far
## with the other. This may contain variables, the other may contain
## existentials but not variables.
## Return [] if impossible.
## Return [({}, None)] if no new bindings
## Return [( {var1: val1, var2: val2, ...}, reason) ...] if match.
## bindings is a dictionary."""
## assert type(bindings) is type({})
## if self is other: return [({}, None)]
## return []
def occurringIn(self, vars):
return Set()
def __repr__(self):
return "()"
def __getitem__(self, i):
raise ValueError("Index %i exceeds size of empty list %s" % (i, `self`))
class FragmentNil(EmptyList, Fragment):
" This is unique in being both a symbol and a list"
def __init__(self, resource, fragid):
Fragment.__init__(self, resource, fragid)
EmptyList.__init__(self, self.store, None, None)
self._asList = self
def unifySequence(self, other, vars=Set([]), existentials=Set([]), bindings={},
start=0):
"""Utility routine to unify 2 python sequences of things against each
other. Slight optimization to iterate instead of recurse when no
binding happens.
"""
if diag.chatty_flag > 99: progress("Unifying sequence %s with %s" %
(`self`, `other`))
i = start
if len(self) != len(other): return []
while 1:
nbs = unify(self[i], other[i], vars, existentials, bindings)
if nbs == []: return [] # Match fail
i = i + 1
if i == len(self): return nbs
if nbs != [({}, None)]: break # Multiple bundings
try:
for a,b in nbs: pass