string_primitives.py 2.37 KB
Newer Older
Tobias Pape's avatar
Tobias Pape committed
1 2
from rpython.rlib.objectmodel import compute_identity_hash

Stefan Marr's avatar
Stefan Marr committed
3 4 5
from som.primitives.primitives import Primitives
from som.vmobjects.primitive import Primitive

6

7 8 9 10 11 12
def _concat(ivkbl, frame, interpreter):
    argument = frame.pop()
    rcvr     = frame.pop()
    frame.push(interpreter.get_universe().new_string(rcvr.get_embedded_string()
                                   + argument.get_embedded_string()))

13

14 15 16 17
def _asSymbol(ivkbl, frame, interpreter):
    rcvr = frame.pop()
    frame.push(interpreter.get_universe().symbol_for(rcvr.get_embedded_string()))

18

19 20
def _length(ivkbl, frame, interpreter):
    rcvr = frame.pop()
21
    frame.push(interpreter.get_universe().new_integer(len(rcvr.get_embedded_string())))
22

23

24 25 26
def _equals(ivkbl, frame, interpreter):
    op1 = frame.pop()
    op2 = frame.pop() # rcvr
27 28
    universe = interpreter.get_universe()
    if op1.get_class(universe) == universe.stringClass:
29
        if op1.get_embedded_string() == op2.get_embedded_string():
30
            frame.push(universe.trueObject)
31
            return
32
    frame.push(universe.falseObject)
33

34

35 36 37 38 39
def _substring(ivkbl, frame, interpreter):
    end   = frame.pop()
    start = frame.pop()
    rcvr  = frame.pop()

40 41
    s      = start.get_embedded_integer() - 1
    e      = end.get_embedded_integer()
42 43
    string = rcvr.get_embedded_string()
    
44
    if s < 0 or s >= len(string) or e > len(string) or e < s: 
45 46 47
        frame.push(interpreter.get_universe().new_string("Error - index out of bounds"))
    else:
        frame.push(interpreter.get_universe().new_string(string[s:e]))
48

49

50 51
def _hashcode(ivkbl, frame, interpreter):
    rcvr = frame.pop()
Tobias Pape's avatar
Tobias Pape committed
52
    frame.push(interpreter.get_universe().new_integer(
Tobias Pape's avatar
Tobias Pape committed
53
        compute_identity_hash(rcvr.get_embedded_string())))
54

55

Stefan Marr's avatar
Stefan Marr committed
56 57
class StringPrimitives(Primitives):
    
58 59 60 61 62
    def install_primitives(self):        
        self._install_instance_primitive(Primitive("concatenate:",          self._universe, _concat))
        self._install_instance_primitive(Primitive("asSymbol",              self._universe, _asSymbol))
        self._install_instance_primitive(Primitive("length",                self._universe, _length))
        self._install_instance_primitive(Primitive("=",                     self._universe, _equals))
Stefan Marr's avatar
Stefan Marr committed
63
        self._install_instance_primitive(Primitive("primSubstringFrom:to:", self._universe, _substring))
64
        self._install_instance_primitive(Primitive("hashcode",              self._universe, _hashcode))