我正在Python中學習詞法分析器。我正在使用Ply庫進行一些字符串的詞法分析。我爲一些C++語言語法實現了以下詞法分析器。詞法分析
但是,我正面臨一個奇怪的行爲。當我在其他函數定義的末尾定義評論states function definitions
時,代碼工作正常。如果我在定義其他定義之前定義了評論state functions
,那麼只要輸入字符串中的//
sectoin開始,就會收到錯誤。
這是什麼原因?
import ply.lex as lex
tokens = (
'DLANGLE', # <<
'DRANGLE', # >>
'EQUAL', # =
'STRING', # "144"
'WORD', # 'Welcome' in "Welcome."
'SEMICOLON', # ;
)
t_ignore = ' \t\v\r' # shortcut for whitespace
states = (
('cppcomment', 'exclusive'), # <!--
)
def t_cppcomment(t): # definition here causes errors
r'//'
print 'MyCOm:',t.value
t.lexer.begin('cppcomment');
def t_cppcomment_end(t):
r'\n'
t.lexer.begin('INITIAL');
def t_cppcomment_error(t):
print "Error FOUND"
t.lexer.skip(1)
def t_DLANGLE(t):
r'<<'
print 'MyLAN:',t.value
return t
def t_DRANGLE(t):
r'>>'
return t
def t_SEMICOLON(t):
r';'
print 'MySemi:',t.value
return t;
def t_EQUAL(t):
r'='
return t
def t_STRING(t):
r'"[^"]*"'
t.value = t.value[1:-1] # drop "surrounding quotes"
print 'MyString:',t.value
return t
def t_WORD(t):
r'[^ <>\n]+'
print 'MyWord:',t.value
return t
webpage = "cout<<\"Hello World\"; // this comment"
htmllexer = lex.lex()
htmllexer.input(webpage)
while True:
tok = htmllexer.token()
if not tok: break
print tok
問候
有人有些見解嗎? –
如果您發佈了您的錯誤樣本,它可能會有所幫助。 –
不生成解釋器錯誤,因爲錯誤由t_cppcomment_error()模塊處理。我的問題是,如果我在最後定義了所有的註釋模塊,但是在註釋模塊在其他模塊 –