388 def Parse(self, Tokens, InputSize):
389
390
391
392
393 ReadCount = 0
394
395 Stack = [ 0 ]
396 MatchedStack = []
397
398 if ReadCount < InputSize:
399 Tokens, CurrentIn = Read(Tokens)
400 CurrentIn = "'" + CurrentIn + "'"
401 ReadCount +=1
402 else:
403 CurrentIn = "'$end'"
404
405
406
407
408 while True:
409
410 Top = GetTop(Stack)
411
412
413
414 Action = self.ParseTable.action[Top][CurrentIn]
415
416
417 Type = None
418 StateId = None
419 for Element in Action:
420 Type = Element[0]
421 StateId = Element[1]
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438 if Type == 'S':
439 Stack.append(CurrentIn)
440 Stack.append(StateId)
441
442 if ReadCount < InputSize:
443 Tokens, CurrentIn = Read(Tokens)
444 CurrentIn = "'" + CurrentIn + "'"
445 ReadCount += 1
446 else:
447 CurrentIn = "'$end'"
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 elif Type == 'R':
473
474 def get_length(Rhs):
475 i = 0
476 for X in Rhs:
477 if self.IsSemanticRule(X):
478 continue
479 elif X == 'eps':
480 continue
481 i += 1
482 return i
483
484
485
486
487
488 Lhs = self.LhsList[StateId - 1]
489 Rhs = self.RhsList[StateId - 1]
490 RhsLen = get_length(Rhs)
491
492 SemanticRule = self.SemanticList[StateId - 1]
493
494
495 Operand = None
496 for i in range(RhsLen * 2):
497 Temp = Stack.pop()
498
499 if type(Temp) == str:
500 print("Temp : ", Temp)
501 Operand = Temp
502 if SemanticRule == "@PUSH":
503 MatchedStack.append(Operand)
504 if SemanticRule == "@GT":
505 print("Matched Stack:", end = " ")
506 print(MatchedStack)
507
508 Operand0 = MatchedStack.pop()
509 Operand1 = MatchedStack.pop()
510 print("GT ", Operand0, " ", Operand1)
511 MatchedStack.append(Operand0)
512
513 if SemanticRule == "@LT":
514 print("Matched Stack:", end = " ")
515 print(MatchedStack)
516
517 Operand0 = MatchedStack.pop()
518 Operand1 = MatchedStack.pop()
519 print("LT ", Operand0, " ", Operand1)
520 MatchedStack.append(Operand0)
521
522 elif SemanticRule == "@AND":
523 print("Matched Stack:", end = " ")
524 print(MatchedStack)
525
526 Operand0 = MatchedStack.pop()
527 Operand1 = MatchedStack.pop()
528 print("AND ", Operand0, " ", Operand1)
529 MatchedStack.append(Operand0)
530
531
532
533 StateId = GetTop(Stack)
534
535 Top = GetTop(Stack)
536 Stack.append(Lhs)
537
538
539 LhsNonTerm = None
540 for NonTerm in self.ParseTable.nonterms:
541 if Lhs == NonTerm.name:
542 LhsNonTerm = NonTerm
543
544
545 Goto = self.ParseTable.goto[StateId][LhsNonTerm]
546
547 Stack.append(Goto)
548
549
550
551
552
553
554 elif Type == 'accept':
555
556
557
558 return Tokens
559 else :
560
561
562
563
564
565 pass
566
567
568
569
570
571