parser.py 23.7 KB
Newer Older
1 2 3 4
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
5

6
from ..vmobjects.integer import integer_value_fits
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

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
56 57
class Parser(object):
    
58
    _single_op_syms        = [Symbol.Not,  Symbol.And,  Symbol.Or,    Symbol.Star,
Stefan Marr's avatar
Stefan Marr committed
59 60
                              Symbol.Div,  Symbol.Mod,  Symbol.Plus,  Symbol.Equal,
                              Symbol.More, Symbol.Less, Symbol.Comma, Symbol.At,
61
                              Symbol.Per,  Symbol.NONE]
Stefan Marr's avatar
Stefan Marr committed
62
    
63
    _binary_op_syms        = [Symbol.Or,   Symbol.Comma, Symbol.Minus, Symbol.Equal,
Stefan Marr's avatar
Stefan Marr committed
64 65 66
                              Symbol.Not,  Symbol.And,   Symbol.Or,    Symbol.Star,
                              Symbol.Div,  Symbol.Mod,   Symbol.Plus,  Symbol.Equal,
                              Symbol.More, Symbol.Less,  Symbol.Comma, Symbol.At,
67
                              Symbol.Per,  Symbol.NONE]
Stefan Marr's avatar
Stefan Marr committed
68
    
69
    _keyword_selector_syms = [Symbol.Keyword, Symbol.KeywordSequence]
Stefan Marr's avatar
Stefan Marr committed
70
  
71
    def __init__(self, reader, file_name, universe):
Stefan Marr's avatar
Stefan Marr committed
72
        self._universe = universe
73
        self._file_name = file_name
Stefan Marr's avatar
Stefan Marr committed
74 75 76 77 78 79
        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()
80

Stefan Marr's avatar
Stefan Marr committed
81 82 83 84 85
    def classdef(self, cgenc):
        cgenc.set_name(self._universe.symbol_for(self._text))
        self._expect(Symbol.Identifier)
        self._expect(Symbol.Equal)
 
86
        self._superclass(cgenc)
Stefan Marr's avatar
Stefan Marr committed
87 88 89 90
  
        self._expect(Symbol.NewTerm)
        self._instance_fields(cgenc)
        
91
        while (self._sym_is_identifier() or self._sym == Symbol.Keyword or
Stefan Marr's avatar
Stefan Marr committed
92 93 94 95 96 97 98 99 100
               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():
101 102
                cgenc.add_instance_method(
                    mgenc.assemble_primitive(self._universe))
Stefan Marr's avatar
Stefan Marr committed
103
            else:
104 105
                cgenc.add_instance_method(
                    mgenc.assemble(self._universe))
Stefan Marr's avatar
Stefan Marr committed
106 107 108 109 110

        if self._accept(Symbol.Separator):
            cgenc.set_class_side(True)
            self._class_fields(cgenc)
            
111
            while (self._sym_is_identifier()      or
Stefan Marr's avatar
Stefan Marr committed
112 113 114 115 116 117 118 119 120 121
                   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():
122 123
                    cgenc.add_class_method(
                        mgenc.assemble_primitive(self._universe))
Stefan Marr's avatar
Stefan Marr committed
124
                else:
125 126
                    cgenc.add_class_method(
                        mgenc.assemble(self._universe))
Stefan Marr's avatar
Stefan Marr committed
127 128 129
        
        self._expect(Symbol.EndTerm)

130 131 132 133 134 135 136 137 138 139 140 141
    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)
142 143 144
            if not super_class:
                raise ParseError("Super class %s could not be loaded"
                                 % super_name.get_string(), Symbol.NONE, self)
145 146 147 148
            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())
149 150 151 152 153 154 155 156 157 158 159 160
        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
161 162 163
    def _sym_in(self, symbol_list):
        return self._sym in symbol_list

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

Stefan Marr's avatar
Stefan Marr committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    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
182 183
        raise ParseError("Unexpected symbol. Expected %(expected)s, but found "
                         "%(found)s", s, self)
Stefan Marr's avatar
Stefan Marr committed
184 185 186 187

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

Stefan Marr's avatar
Stefan Marr committed
192 193
    def _instance_fields(self, cgenc):
        if self._accept(Symbol.Or):
194
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
195 196 197 198 199 200
                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):
201
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
                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):
219
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
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
            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)
246

Stefan Marr's avatar
Stefan Marr committed
247 248 249 250 251 252 253 254
        # 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()
255

Stefan Marr's avatar
Stefan Marr committed
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
        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
296
    def _locals(self, mgenc):
297
        while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
298 299 300 301 302 303 304 305 306 307 308 309 310
            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
311
            mgenc.set_finished()
Stefan Marr's avatar
Stefan Marr committed
312 313 314 315 316 317 318 319 320 321 322 323
        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)
324

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

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

Stefan Marr's avatar
Stefan Marr committed
334 335 336 337 338 339 340 341 342 343
        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
344
    def _assignation(self, mgenc):
Stefan Marr's avatar
Stefan Marr committed
345
        l = []
346

Stefan Marr's avatar
Stefan Marr committed
347 348 349 350 351 352 353 354 355 356
        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):
357
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
358 359 360 361 362 363 364 365 366
            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)
367

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

Stefan Marr's avatar
Stefan Marr committed
371 372 373 374 375
    def _evaluation(self, mgenc):
        # single: superSend
        is_super_send = [False]
 
        self._primary(mgenc, is_super_send)
376
        if (self._sym_is_identifier()            or
Stefan Marr's avatar
Stefan Marr committed
377 378 379 380 381 382 383 384
            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
        
385
        if self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399
            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)
400

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

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

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

Stefan Marr's avatar
Stefan Marr committed
412
    def _messages(self, mgenc, is_super_send):
413 414
        if self._sym_is_identifier():
            while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
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
                # 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)

449 450 451 452
    @staticmethod
    def _is_quick_send(msg):
        return msg.get_string() == "+"

Stefan Marr's avatar
Stefan Marr committed
453 454 455 456
    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
457
        self._binary_operand(mgenc, [False])
458

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

    def _binary_operand(self, mgenc, is_super_send):
        self._primary(mgenc, is_super_send)
 
469
        while self._sym_is_identifier():
Stefan Marr's avatar
Stefan Marr committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
            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)
488

Stefan Marr's avatar
Stefan Marr committed
489 490 491 492 493 494 495 496
    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
497
        while self._sym == Symbol.OperatorSequence or self._sym_in(self._binary_op_syms):
Stefan Marr's avatar
Stefan Marr committed
498
            self._binary_message(mgenc, [False])
499

Stefan Marr's avatar
Stefan Marr committed
500 501 502 503 504 505 506 507 508 509 510 511
    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)
512

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

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

522 523 524 525 526 527
    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
528 529 530

    def _negative_decimal(self):
        self._expect(Symbol.Minus)
531
        return self._literal_decimal(True)
Stefan Marr's avatar
Stefan Marr committed
532
 
533
    def _literal_integer(self, negate_value):
534 535 536 537 538 539 540 541
        try:
            i = int(self._text)
            if negate_value:
                i = 0 - i
        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
542 543
        self._expect(Symbol.Integer)

544 545 546 547 548 549 550
        if integer_value_fits(i):
            return self._universe.new_integer(i)
        else:
            return self._universe.new_biginteger(i)


    def _literal_double(self, negate_value):
551 552 553 554 555 556 557 558
        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)
559 560
        self._expect(Symbol.Double)
        return self._universe.new_double(f)
Stefan Marr's avatar
Stefan Marr committed
561 562 563 564 565 566 567 568 569 570 571
 
    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)
572

Stefan Marr's avatar
Stefan Marr committed
573 574 575 576 577 578 579 580 581
    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):
Stefan Marr's avatar
Stefan Marr committed
582 583
        if (self._sym == Symbol.OperatorSequence or
            self._sym_in(self._single_op_syms)):
Stefan Marr's avatar
Stefan Marr committed
584
            return self._binary_selector()
Stefan Marr's avatar
Stefan Marr committed
585 586
        if (self._sym == Symbol.Keyword or
            self._sym == Symbol.KeywordSequence):
Stefan Marr's avatar
Stefan Marr committed
587
            return self._keyword_selector()
Stefan Marr's avatar
Stefan Marr committed
588
        return self._unary_selector()
Stefan Marr's avatar
Stefan Marr committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602
 
    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)
603 604 605

        mgenc.add_argument_if_absent("$blockSelf")

Stefan Marr's avatar
Stefan Marr committed
606 607
        if self._sym == Symbol.Colon:
            self._block_pattern(mgenc)
608

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

Stefan Marr's avatar
Stefan Marr committed
614
        mgenc.set_signature(self._universe.symbol_for(block_sig))
615

Stefan Marr's avatar
Stefan Marr committed
616
        self._block_contents(mgenc)
617

Stefan Marr's avatar
Stefan Marr committed
618 619 620 621 622 623 624 625 626 627 628 629
        # 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)
630

Stefan Marr's avatar
Stefan Marr committed
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
    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()