Advertisement
Guest User

Untitled

a guest
Dec 10th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import ply.lex as lex
  2. import ply.yacc as yacc
  3.  
  4. # List of token names. This is always required.
  5. tokens = (
  6. 'CLB',
  7. 'CRB',
  8. 'Colon',
  9. 'Comma',
  10. 'Number',
  11. 'String',
  12. 'True',
  13. 'False',
  14. 'Null',
  15. 'LSB',
  16. 'RSB'
  17. )
  18.  
  19. # Regular expression rules for simple tokens
  20. t_CLB = r'\{'
  21. t_CRB = r'\}'
  22. t_Colon = r':'
  23. t_Comma = r','
  24. t_LSB = r'\['
  25. t_RSB = r'\]'
  26.  
  27.  
  28. def t_Number(t):
  29. r'(-?)(0|([1-9][0-9]*))((\.[0-9]*)?)(([eE]((\+|-)?)(([0-9])*))?)'
  30. return t
  31.  
  32.  
  33. def t_String(t):
  34. r'\"([^"\\\u0000-\u001F\u007F-\u009F]|(\\["/\\bfnrtu0000-uFFFF]))*\"'
  35. return t
  36.  
  37.  
  38. def t_True(t):
  39. r'true'
  40. t.value = True
  41. return t
  42.  
  43.  
  44. def t_False(t):
  45. r'false'
  46. t.value = False
  47. return t
  48.  
  49.  
  50. def t_Null(t):
  51. r'null'
  52. t.value = None
  53. return t
  54.  
  55.  
  56. def t_newline(t):
  57. r'\n+'
  58. lexer.lineno += len(t.value)
  59.  
  60.  
  61. # Error handling rule
  62. def t_error(t):
  63. print('Illegal character "%s"' % t.value[0])
  64.  
  65.  
  66. # String containing ignored characters (spaces and tabs)
  67. t_ignore = ' \t'
  68.  
  69.  
  70. # Build the lexer
  71. lexer = lex.lex()
  72.  
  73.  
  74. def p_Value(p):
  75. """
  76. Value : Number
  77. | String
  78. | True
  79. | Null
  80. | False
  81. | Object
  82. | Array """
  83.  
  84.  
  85. def p_Object(p):
  86. '''
  87. Object : CLB pairs CRB
  88. '''
  89.  
  90.  
  91. def p_pairs(p):
  92. '''
  93. pairs : pair
  94. |
  95. '''
  96.  
  97.  
  98. def p_pair(p):
  99. '''
  100. pair : String Colon Value Comma pair
  101. | String Colon Value
  102. '''
  103.  
  104.  
  105. def p_Array(p):
  106. '''
  107. Array : LSB Valuesf RSB
  108. '''
  109.  
  110.  
  111. def p_Values(p):
  112. '''
  113. Values : Value Comma Value
  114. | Value
  115. '''
  116.  
  117. def p_Valuesf(p):
  118. '''
  119. Valuesf : Values
  120. |
  121. '''
  122.  
  123. def p_error(p):
  124. print('Incorrect Syntax')
  125.  
  126.  
  127. yacc.yacc()
  128.  
  129. data = '[1,2,3]'
  130.  
  131. print(yacc.parse(data))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement