parser.py 24 KB
Newer Older
Stefan Marr's avatar
Stefan Marr committed
1 2
from rpython.rlib.rarithmetic import string_to_int
from rpython.rlib.rbigint import rbigint
3
from rpython.rlib.rstring import ParseStringOverflowError
4 5 6 7
from .lexer                     import Lexer
from .bytecode_generator        import BytecodeGenerator
from .method_generation_context import MethodGenerationContext
from .symbol                    import Symbol, symbol_as_str
Stefan Marr's avatar
Stefan Marr committed
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

class ParseError(BaseException):
    def __init__(self, message, expected_sym, parser):
        self._message           = message
        self._line              = parser._lexer.get_current_line_number()
        self._column            = parser._lexer.get_current_column()
        self._text              = parser._text
        self._raw_buffer        = parser._lexer.get_raw_buffer()
        self._file_name         = parser._file_name
        self._expected_sym      = expected_sym
        self._found_sym         = parser._sym

    def _is_printable_symbol(self):
        return (self._found_sym == Symbol.Integer or
                self._found_sym == Symbol.Double  or
                self._found_sym >= Symbol.STString)

    def _expected_sym_str(self):
        return symbol_as_str(self._expected_sym)

    def __str__(self):
        msg = "%(file)s:%(line)d:%(column)d: error: " + self._message
        if self._is_printable_symbol():
            found = "%s (%s)" % (symbol_as_str(self._found_sym), self._text)
        else:
            found = symbol_as_str(self._found_sym)
        msg += ": %s" % self._raw_buffer

        expected = self._expected_sym_str()

        return (msg % {
            'file'       : self._file_name,
            'line'       : self._line,
            'column'     : self._column,
            'expected'   : expected,
            'found'      : found})


class ParseErrorSymList(ParseError):

    def __init__(self, message, expected_syms, parser):
        ParseError.__init__(self, message, 0, parser)
        self._expected_syms = expected_syms

    def _expected_sym_str(self):
        return  ", ".join([symbol_as_str(x) for x in self._expected_syms])


Stefan Marr's avatar
Stefan Marr committed
57 58
class Parser(object):
    
59
    _single_op_syms        = [Symbol.Not,  Symbol.And,  Symbol.Or,    Symbol.Star,
Stefan Marr's avatar
Stefan Marr committed
60 61
                              Symbol.Div,  Symbol.Mod,  Symbol.Plus,  Symbol.Equal,
                              Symbol.More, Symbol.Less, Symbol.Comma, Symbol.At,
62
                              Symbol.Per,  Symbol.NONE]
Stefan Marr's avatar
Stefan Marr committed
63
    
64
    _binary_op_syms        = [Symbol.Or,   Symbol.Comma, Symbol.Minus, Symbol.Equal,
Stefan Marr's avatar
Stefan Marr committed
65 66 67
                              Symbol.Not,  Symbol.And,   Symbol.Or,    Symbol.Star,
                              Symbol.Div,  Symbol.Mod,   Symbol.Plus,  Symbol.Equal,
                              Symbol.More, Symbol.Less,  Symbol.Comma, Symbol.At,
68
                              Symbol.Per,  Symbol.NONE]
Stefan Marr's avatar
Stefan Marr committed
69
    
70
    _keyword_selector_syms = [Symbol.Keyword, Symbol.KeywordSequence]
Stefan Marr's avatar
Stefan Marr committed
71
  
72
    def __init__(self, reader, file_name, universe):
Stefan Marr's avatar
Stefan Marr committed
73
        self._universe = universe
74
        self._file_name = file_name
Stefan Marr's avatar
Stefan Marr committed
75 76 77 78 79 80
        self._lexer    = Lexer(reader)
        self._bc_gen   = BytecodeGenerator()
        self._sym      = Symbol.NONE
        self._text     = None
        self._next_sym = Symbol.NONE
        self._get_symbol_from_lexer()
81

Stefan Marr's avatar
Stefan Marr committed
82 83 84 85 86
    def classdef(self, cgenc):
        cgenc.set_name(self._universe.symbol_for(self._text))
        self._expect(Symbol.Identifier)
        self._expect(Symbol.Equal)
 
87
        self._superclass(cgenc)
Stefan Marr's avatar
Stefan Marr committed
88 89 90 91
  
        self._expect(Symbol.NewTerm)
        self._instance_fields(cgenc)
        
92
        while (self._sym_is_identifier() or self._sym == Symbol.Keyword or
Stefan Marr's avatar
Stefan Marr committed
93 94 95 96 97 98 99 100 101
               self._sym == Symbol.OperatorSequence or
               self._sym_in(self._binary_op_syms)):
            mgenc = MethodGenerationContext()
            mgenc.set_holder(cgenc)
            mgenc.add_argument("self")
         
            self._method(mgenc)
         
            if mgenc.is_primitive():
102 103
                cgenc.add_instance_method(
                    mgenc.assemble_primitive(self._universe))
Stefan Marr's avatar
Stefan Marr committed
104
            else:
105 106
                cgenc.add_instance_method(
                    mgenc.assemble(self._universe))
Stefan Marr's avatar
Stefan Marr committed
107 108 109 110 111

        if self._accept(Symbol.Separator):
            cgenc.set_class_side(True)
            self._class_fields(cgenc)
            
112
            while (self._sym_is_identifier()      or
Stefan Marr's avatar
Stefan Marr committed
113 114 115 116 117 118 119 120 121 122
                   self._sym == Symbol.Keyword    or
                   self._sym == Symbol.OperatorSequence or
                   self._sym_in(self._binary_op_syms)):
                mgenc = MethodGenerationContext()
                mgenc.set_holder(cgenc)
                mgenc.add_argument("self")
         
                self._method(mgenc)
         
                if mgenc.is_primitive():
123 124
                    cgenc.add_class_method(
                        mgenc.assemble_primitive(self._universe))
Stefan Marr's avatar
Stefan Marr committed
125
                else:
126 127
                    cgenc.add_class_method(
                        mgenc.assemble(self._universe))
Stefan Marr's avatar
Stefan Marr committed
128 129 130
        
        self._expect(Symbol.EndTerm)

131 132 133 134 135 136 137 138 139 140 141 142
    def _superclass(self, cgenc):
        if self._sym == Symbol.Identifier:
            super_name = self._universe.symbol_for(self._text)
            self._accept(Symbol.Identifier)
        else:
            super_name = self._universe.symbol_for("Object")
        
        cgenc.set_super_name(super_name)
 
        # Load the super class, if it is not nil (break the dependency cycle)
        if super_name.get_string() != "nil":
            super_class = self._universe.load_class(super_name)
143 144 145
            if not super_class:
                raise ParseError("Super class %s could not be loaded"
                                 % super_name.get_string(), Symbol.NONE, self)
146 147 148 149
            cgenc.set_instance_fields_of_super(
                super_class.get_instance_fields())
            cgenc.set_class_fields_of_super(
                super_class.get_class(self._universe).get_instance_fields())
150 151 152 153 154 155 156 157 158 159 160 161
        else:
            # WARNING:
            # We hardcode here the field names for Class
            # since Object class superclass = Class
            # We avoid here any kind of dynamic solution to avoid further
            # complexity. However, that makes it static, it is going to make it
            #  harder to change the definition of Class and Object
            field_names_of_class = ["class", "superClass", "name",
                                    "instanceFields", "instanceInvokables"]
            field_names = self._universe.new_array_with_strings(field_names_of_class)
            cgenc.set_class_fields_of_super(field_names)

Stefan Marr's avatar
Stefan Marr committed
162 163 164
    def _sym_in(self, symbol_list):
        return self._sym in symbol_list

165 166 167
    def _sym_is_identifier(self):
        return self._sym == Symbol.Identifier or self._sym == Symbol.Primitive

Stefan Marr's avatar
Stefan Marr committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    def _accept(self, s):
        if self._sym == s:
            self._get_symbol_from_lexer()
            return True
        return False

    def _accept_one_of(self, symbol_list):
        if self._sym_in(symbol_list):
            self._get_symbol_from_lexer()
            return True
        return False
  
    def _expect(self, s):
        if self._accept(s):
            return True
183 184
        raise ParseError("Unexpected symbol. Expected %(expected)s, but found "
                         "%(found)s", s, self)
Stefan Marr's avatar
Stefan Marr committed
185 186 187 188

    def _expect_one_of(self, symbol_list):
        if self._accept_one_of(symbol_list):
            return True
189 190 191
        raise ParseErrorSymList("Unexpected symbol. Expected one of "
                                "%(expected)s, but found %(found)s",
                                symbol_list, self)
192

Stefan Marr's avatar
Stefan Marr committed
193 194
    def _instance_fields(self, cgenc):
        if self._accept(Symbol.Or):
195
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
196 197 198 199 200 201
                var = self._variable()
                cgenc.add_instance_field(self._universe.symbol_for(var))
            self._expect(Symbol.Or)
 
    def _class_fields(self, cgenc):
        if self._accept(Symbol.Or):
202
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                var = self._variable()
                cgenc.add_class_field(self._universe.symbol_for(var))
            self._expect(Symbol.Or)

    def _method(self, mgenc):
        self._pattern(mgenc)
        self._expect(Symbol.Equal)
        if self._sym == Symbol.Primitive:
            mgenc.set_primitive(True)
            self._primitive_block()
        else:
            self._method_block(mgenc)

    def _primitive_block(self):
        self._expect(Symbol.Primitive)

    def _pattern(self, mgenc):
220
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
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
            self._unary_pattern(mgenc)
        elif self._sym == Symbol.Keyword:
            self._keyword_pattern(mgenc)
        else:
            self._binary_pattern(mgenc)

    def _unary_pattern(self, mgenc):
        mgenc.set_signature(self._unary_selector())

    def _binary_pattern(self, mgenc):
        mgenc.set_signature(self._binary_selector())
        mgenc.add_argument_if_absent(self._argument())
 
    def _keyword_pattern(self, mgenc):
        kw = self._keyword()
        mgenc.add_argument_if_absent(self._argument())
        
        while self._sym == Symbol.Keyword:
            kw += self._keyword()
            mgenc.add_argument_if_absent(self._argument())
            
        mgenc.set_signature(self._universe.symbol_for(kw))

    def _method_block(self, mgenc):
        self._expect(Symbol.NewTerm)
        self._block_contents(mgenc)
247

Stefan Marr's avatar
Stefan Marr committed
248 249 250 251 252 253 254 255
        # if no return has been generated so far, we can be sure there was no .
        # terminating the last expression, so the last expression's value must
        # be popped off the stack and a ^self be generated
        if not mgenc.is_finished():
            self._bc_gen.emitPOP(mgenc)
            self._bc_gen.emitPUSHARGUMENT(mgenc, 0, 0)
            self._bc_gen.emitRETURNLOCAL(mgenc)
            mgenc.set_finished()
256

Stefan Marr's avatar
Stefan Marr committed
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
        self._expect(Symbol.EndTerm)

    def _unary_selector(self):
        return self._universe.symbol_for(self._identifier())
 
    def _binary_selector(self):
        s = self._text
 
        if    self._accept(Symbol.Or):                     pass
        elif  self._accept(Symbol.Comma):                  pass
        elif  self._accept(Symbol.Minus):                  pass
        elif  self._accept(Symbol.Equal):                  pass
        elif  self._accept_one_of(self._single_op_syms):   pass
        elif  self._accept(Symbol.OperatorSequence):       pass
        else: self._expect(Symbol.NONE)
  
        return self._universe.symbol_for(s)
 
    def _identifier(self):
        s = self._text
        is_primitive = self._accept(Symbol.Primitive)
        if not is_primitive:
            self._expect(Symbol.Identifier)
        return s

    def _keyword(self):
        s = self._text
        self._expect(Symbol.Keyword)
        return s

    def _argument(self):
        return self._variable()

    def _block_contents(self, mgenc):
        if self._accept(Symbol.Or):
            self._locals(mgenc)
            self._expect(Symbol.Or)
  
        self._block_body(mgenc, False)

Stefan Marr's avatar
Stefan Marr committed
297
    def _locals(self, mgenc):
298
        while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
299 300 301 302 303 304 305 306 307 308 309 310 311
            mgenc.add_local_if_absent(self._variable())

    def _block_body(self, mgenc, seenPeriod):
        if self._accept(Symbol.Exit):
            self._result(mgenc)
        elif self._sym == Symbol.EndBlock:
            if seenPeriod:
                # a POP has been generated which must be elided (blocks always
                # return the value of the last expression, regardless of
                # whether it was terminated with a . or not)
                mgenc.remove_last_bytecode()
            
            self._bc_gen.emitRETURNLOCAL(mgenc)
Stefan Marr's avatar
Stefan Marr committed
312
            mgenc.set_finished()
Stefan Marr's avatar
Stefan Marr committed
313 314 315 316 317 318 319 320 321 322 323 324
        elif self._sym == Symbol.EndTerm:
            # it does not matter whether a period has been seen, as the end of
            # the method has been found (EndTerm) - so it is safe to emit a
            # "return self"
            self._bc_gen.emitPUSHARGUMENT(mgenc, 0, 0)
            self._bc_gen.emitRETURNLOCAL(mgenc)
            mgenc.set_finished()
        else:
            self._expression(mgenc)
            if self._accept(Symbol.Period):
                self._bc_gen.emitPOP(mgenc)
                self._block_body(mgenc, True)
325

Stefan Marr's avatar
Stefan Marr committed
326 327
    def _result(self, mgenc):
        self._expression(mgenc)
328 329
        self._accept(Symbol.Period)

Stefan Marr's avatar
Stefan Marr committed
330 331 332 333
        if mgenc.is_block_method():
            self._bc_gen.emitRETURNNONLOCAL(mgenc)
        else:
            self._bc_gen.emitRETURNLOCAL(mgenc)
334

Stefan Marr's avatar
Stefan Marr committed
335 336 337 338 339 340 341 342 343 344
        mgenc.set_finished(True)

    def _expression(self, mgenc):
        self._peek_for_next_symbol_from_lexer()
 
        if self._next_sym == Symbol.Assign:
            self._assignation(mgenc)
        else:
            self._evaluation(mgenc)

Stefan Marr's avatar
Stefan Marr committed
345
    def _assignation(self, mgenc):
Stefan Marr's avatar
Stefan Marr committed
346
        l = []
347

Stefan Marr's avatar
Stefan Marr committed
348 349 350 351 352 353 354 355 356 357
        self._assignments(mgenc, l)
        self._evaluation(mgenc)
 
        for assignment in l:
            self._bc_gen.emitDUP(mgenc)
  
        for assignment in l:
            self._gen_pop_variable(mgenc, assignment)

    def _assignments(self, mgenc, l):
358
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
359 360 361 362 363 364 365 366 367
            l.append(self._assignment(mgenc))
            self._peek_for_next_symbol_from_lexer()
            if self._next_sym == Symbol.Assign:
                self._assignments(mgenc, l)

    def _assignment(self, mgenc):
        v   = self._variable()
        var = self._universe.symbol_for(v)
        mgenc.add_literal_if_absent(var)
368

Stefan Marr's avatar
Stefan Marr committed
369 370
        self._expect(Symbol.Assign)
        return v
371

Stefan Marr's avatar
Stefan Marr committed
372 373 374 375 376
    def _evaluation(self, mgenc):
        # single: superSend
        is_super_send = [False]
 
        self._primary(mgenc, is_super_send)
377
        if (self._sym_is_identifier()            or
Stefan Marr's avatar
Stefan Marr committed
378 379 380 381 382 383 384 385
            self._sym == Symbol.Keyword          or 
            self._sym == Symbol.OperatorSequence or
            self._sym_in(self._binary_op_syms)):
            self._messages(mgenc, is_super_send)
 
    def _primary(self, mgenc, is_super_send):
        is_super_send[0] = False
        
386
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400
            v = self._variable()
            if v == "super":
                is_super_send[0] = True
                # sends to super push self as the receiver
                v = "self"
            self._gen_push_variable(mgenc, v)

        elif self._sym == Symbol.NewTerm:
            self._nested_term(mgenc)
        elif self._sym == Symbol.NewBlock:
            bgenc = MethodGenerationContext()
            bgenc.set_is_block_method(True)
            bgenc.set_holder(mgenc.get_holder())
            bgenc.set_outer(mgenc)
401

Stefan Marr's avatar
Stefan Marr committed
402
            self._nested_block(bgenc)
403

Stefan Marr's avatar
Stefan Marr committed
404 405 406 407 408
            block_method = bgenc.assemble(self._universe)
            mgenc.add_literal(block_method)
            self._bc_gen.emitPUSHBLOCK(mgenc, block_method)
        else:
            self._literal(mgenc)
409

Stefan Marr's avatar
Stefan Marr committed
410 411
    def _variable(self):
        return self._identifier()
412

Stefan Marr's avatar
Stefan Marr committed
413
    def _messages(self, mgenc, is_super_send):
414 415
        if self._sym_is_identifier():
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
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
                # only the first message in a sequence can be a super send
                self._unary_message(mgenc, is_super_send)
                is_super_send[0] = False

            while (self._sym == Symbol.OperatorSequence or
                   self._sym_in(self._binary_op_syms)):
                self._binary_message(mgenc, [False])
    
            if self._sym == Symbol.Keyword:
                self._keyword_message(mgenc, [False])
        
        elif (self._sym == Symbol.OperatorSequence or
              self._sym_in(self._binary_op_syms)):
            while (self._sym == Symbol.OperatorSequence or
                   self._sym_in(self._binary_op_syms)):
                # only the first message in a sequence can be a super send
                self._binary_message(mgenc, is_super_send)
                is_super_send[0] = False
    
            if self._sym == Symbol.Keyword:
                self._keyword_message(mgenc, [False])
        
        else:
            self._keyword_message(mgenc, is_super_send)

    def _unary_message(self, mgenc, is_super_send):
        msg = self._unary_selector()
        mgenc.add_literal_if_absent(msg)
 
        if is_super_send[0]:
            self._bc_gen.emitSUPERSEND(mgenc, msg)
        else:
            self._bc_gen.emitSEND(mgenc, msg)

450 451
    @staticmethod
    def _is_quick_send(msg):
452 453
        m = msg.get_string()
        return m == "+" or m == "-" or m == "*"
454

Stefan Marr's avatar
Stefan Marr committed
455 456 457 458
    def _binary_message(self, mgenc, is_super_send):
        msg = self._binary_selector()
        mgenc.add_literal_if_absent(msg)
 
Stefan Marr's avatar
Stefan Marr committed
459
        self._binary_operand(mgenc, [False])
460

Stefan Marr's avatar
Stefan Marr committed
461 462
        if is_super_send[0]:
            self._bc_gen.emitSUPERSEND(mgenc, msg)
463 464
        elif self._is_quick_send(msg):
            self._bc_gen.emitQUICKSEND(mgenc, msg)
Stefan Marr's avatar
Stefan Marr committed
465 466 467 468 469 470
        else:
            self._bc_gen.emitSEND(mgenc, msg)

    def _binary_operand(self, mgenc, is_super_send):
        self._primary(mgenc, is_super_send)
 
471
        while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            self._unary_message(mgenc, is_super_send)

    def _keyword_message(self, mgenc, is_super_send):
        kw = self._keyword()
        self._formula(mgenc)
      
        while self._sym == Symbol.Keyword:
            kw += self._keyword()
            self._formula(mgenc)
      
        msg = self._universe.symbol_for(kw)
     
        mgenc.add_literal_if_absent(msg)
     
        if is_super_send[0]:
            self._bc_gen.emitSUPERSEND(mgenc, msg)
        else:
            self._bc_gen.emitSEND(mgenc, msg)
490

Stefan Marr's avatar
Stefan Marr committed
491 492 493 494 495 496 497 498
    def _formula(self, mgenc):
        is_super_send = [False]
        self._binary_operand(mgenc, is_super_send)
     
        # only the first message in a sequence can be a super send
        if self._sym == Symbol.OperatorSequence or self._sym_in(self._binary_op_syms):
            self._binary_message(mgenc, is_super_send)
      
Stefan Marr's avatar
Stefan Marr committed
499
        while self._sym == Symbol.OperatorSequence or self._sym_in(self._binary_op_syms):
Stefan Marr's avatar
Stefan Marr committed
500
            self._binary_message(mgenc, [False])
501

Stefan Marr's avatar
Stefan Marr committed
502 503 504 505 506 507 508 509 510 511 512 513
    def _nested_term(self, mgenc):
        self._expect(Symbol.NewTerm)
        self._expression(mgenc)
        self._expect(Symbol.EndTerm)

    def _literal(self, mgenc):
        if self._sym == Symbol.Pound:
            self._literal_symbol(mgenc)
        elif self._sym == Symbol.STString:
            self._literal_string(mgenc)
        else:
            self._literal_number(mgenc)
514

Stefan Marr's avatar
Stefan Marr committed
515 516
    def _literal_number(self, mgenc):
        if self._sym == Symbol.Minus:
517
            lit = self._negative_decimal()
Stefan Marr's avatar
Stefan Marr committed
518
        else:
519
            lit = self._literal_decimal(False)
520

Stefan Marr's avatar
Stefan Marr committed
521 522
        mgenc.add_literal_if_absent(lit)
        self._bc_gen.emitPUSHCONSTANT(mgenc, lit)
523

524 525 526 527 528 529
    def _literal_decimal(self, negate_value):
        if self._sym == Symbol.Integer:
            return self._literal_integer(negate_value)
        else:
            assert self._sym == Symbol.Double
            return self._literal_double(negate_value)
Stefan Marr's avatar
Stefan Marr committed
530 531 532

    def _negative_decimal(self):
        self._expect(Symbol.Minus)
533
        return self._literal_decimal(True)
Stefan Marr's avatar
Stefan Marr committed
534
 
535
    def _literal_integer(self, negate_value):
536
        try:
Stefan Marr's avatar
Stefan Marr committed
537
            i = string_to_int(self._text)
538 539
            if negate_value:
                i = 0 - i
Stefan Marr's avatar
Stefan Marr committed
540
            result = self._universe.new_integer(i)
541
        except ParseStringOverflowError:
Stefan Marr's avatar
Stefan Marr committed
542 543 544 545
            bigint = rbigint.fromstr(self._text)
            if negate_value:
                bigint.sign = -1
            result = self._universe.new_biginteger(bigint)
546 547 548 549
        except ValueError:
            raise ParseError("Could not parse integer. "
                             "Expected a number but got '%s'" % self._text,
                             Symbol.NONE, self)
Stefan Marr's avatar
Stefan Marr committed
550
        self._expect(Symbol.Integer)
Stefan Marr's avatar
Stefan Marr committed
551
        return result
552 553

    def _literal_double(self, negate_value):
554 555 556 557 558 559 560 561
        try:
            f = float(self._text)
            if negate_value:
                f = 0.0 - f
        except ValueError:
            raise ParseError("Could not parse double. "
                             "Expected a number but got '%s'" % self._text,
                             Symbol.NONE, self)
562 563
        self._expect(Symbol.Double)
        return self._universe.new_double(f)
Stefan Marr's avatar
Stefan Marr committed
564 565 566 567 568 569 570 571 572 573 574
 
    def _literal_symbol(self, mgenc):
        self._expect(Symbol.Pound)
        if self._sym == Symbol.STString:
            s    = self._string()
            symb = self._universe.symbol_for(s)
        else:
            symb = self._selector()
      
        mgenc.add_literal_if_absent(symb)
        self._bc_gen.emitPUSHCONSTANT(mgenc, symb)
575

Stefan Marr's avatar
Stefan Marr committed
576 577 578 579 580 581 582 583 584
    def _literal_string(self, mgenc):
        s = self._string()
     
        string = self._universe.new_string(s)
        mgenc.add_literal_if_absent(string)
     
        self._bc_gen.emitPUSHCONSTANT(mgenc, string)
     
    def _selector(self):
585 586
        if (self._sym == Symbol.OperatorSequence or
            self._sym_in(self._single_op_syms)):
Stefan Marr's avatar
Stefan Marr committed
587
            return self._binary_selector()
588 589
        if (self._sym == Symbol.Keyword or
            self._sym == Symbol.KeywordSequence):
Stefan Marr's avatar
Stefan Marr committed
590
            return self._keyword_selector()
591
        return self._unary_selector()
Stefan Marr's avatar
Stefan Marr committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605
 
    def _keyword_selector(self):
        s = self._text
        self._expect_one_of(self._keyword_selector_syms)
        symb = self._universe.symbol_for(s)
        return symb
 
    def _string(self):
        s = self._text
        self._expect(Symbol.STString)
        return s

    def _nested_block(self, mgenc):
        self._expect(Symbol.NewBlock)
606 607 608

        mgenc.add_argument_if_absent("$blockSelf")

Stefan Marr's avatar
Stefan Marr committed
609 610
        if self._sym == Symbol.Colon:
            self._block_pattern(mgenc)
611

Stefan Marr's avatar
Stefan Marr committed
612
        # generate Block signature
613
        block_sig = "$blockMethod"
Stefan Marr's avatar
Stefan Marr committed
614 615
        arg_size = mgenc.get_number_of_arguments()
        block_sig += ":" * (arg_size - 1)
616

Stefan Marr's avatar
Stefan Marr committed
617
        mgenc.set_signature(self._universe.symbol_for(block_sig))
618

Stefan Marr's avatar
Stefan Marr committed
619
        self._block_contents(mgenc)
620

Stefan Marr's avatar
Stefan Marr committed
621 622 623 624 625 626 627 628 629 630 631 632
        # if no return has been generated, we can be sure that the last
        # expression in the block was not terminated by ., and can generate 
        # a return
        if not mgenc.is_finished():
            self._bc_gen.emitRETURNLOCAL(mgenc)
            mgenc.set_finished(True)
 
        self._expect(Symbol.EndBlock)
 
    def _block_pattern(self, mgenc):
        self._block_arguments(mgenc)
        self._expect(Symbol.Or)
633

Stefan Marr's avatar
Stefan Marr committed
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
    def _block_arguments(self, mgenc):
        self._expect(Symbol.Colon)
        mgenc.add_argument_if_absent(self._argument())
  
        while self._sym == Symbol.Colon:
            self._expect(Symbol.Colon)
            mgenc.add_argument_if_absent(self._argument())
 
    def _gen_push_variable(self, mgenc, var):
        # The purpose of this function is to find out whether the variable to be
        # pushed on the stack is a local variable, argument, or object field.
        # This is done by examining all available lexical contexts, starting with
        # the innermost (i.e., the one represented by mgenc).
 
        # triplet: index, context, isArgument
        triplet = [0, 0, False]
 
        if mgenc.find_var(var, triplet):
            if triplet[2]:
                self._bc_gen.emitPUSHARGUMENT(mgenc, triplet[0], triplet[1])
            else:
                self._bc_gen.emitPUSHLOCAL(mgenc, triplet[0], triplet[1])
        else:
            identifier = self._universe.symbol_for(var)
            if mgenc.has_field(identifier):
                field_name = identifier
                mgenc.add_literal_if_absent(field_name)
                self._bc_gen.emitPUSHFIELD(mgenc, field_name)
            else:
                globe = identifier
                mgenc.add_literal_if_absent(globe)
                self._bc_gen.emitPUSHGLOBAL(mgenc, globe)

    def _gen_pop_variable(self, mgenc, var):
        # The purpose of this function is to find out whether the variable to be
        # popped off the stack is a local variable, argument, or object field.
        # This is done by examining all available lexical contexts, starting with
        # the innermost (i.e., the one represented by mgenc).
 
        # triplet: index, context, isArgument
        triplet = [0, 0, False]
 
        if mgenc.find_var(var, triplet):
            if triplet[2]:
                self._bc_gen.emitPOPARGUMENT(mgenc, triplet[0], triplet[1])
            else:
                self._bc_gen.emitPOPLOCAL(mgenc, triplet[0], triplet[1])
        else:
            self._bc_gen.emitPOPFIELD(mgenc, self._universe.symbol_for(var))

    def _get_symbol_from_lexer(self):
        self._sym  = self._lexer.get_sym()
        self._text = self._lexer.get_text()
    
    def _peek_for_next_symbol_from_lexer(self):
        self._next_sym = self._lexer.peek()