Я реализую интерпретатор для давно -устаревшего языка сценариев текстового редактора, и у меня возникли проблемы с корректной работой лексера.
Вот пример проблемной части языка:
T
L /LOCATE ME/
C /LOCATE ME/CHANGED ME/ * *
C ;CHANGED ME;CHANGED ME AGAIN; 1 *
Символы /
, кажется, заключают строки в кавычки, а также действуют как разделитель для C
(CHANGE
). команда вsed
-синтаксис type, хотя он позволяет использовать любой символ в качестве разделителя.
Вероятно, я реализовал примерно половину наиболее распространенных команд, просто используя parse_tokens(line.split())
. Это было быстро и грязно, но сработало на удивление хорошо.
Чтобы не писать собственный лексер, я попробовал shlex
.
Это работает довольно хорошо, за исключением CHANGE
случаев:
import shlex
def shlex_test(cmd_str):
lex = shlex.shlex(cmd_str)
lex.quotes = '/'
return list(lex)
print(shlex_test('L /spaced string/'))
# OK! gives: ['L', '/spaced string/']
print(shlex_test('C /spaced string/another string/ * *'))
# gives : ['C', '/spaced string/', 'another', 'string/', '*', '*']
# desired : any format that doesn't split on a space between /'s
print(shlex_test('C ;a b;b a;'))
# gives : ['C', ';', 'b', 'a', ';', 'a', 'b', ';']
# desired : same format as CHANGE command above
Кто-нибудь знает простой способ выполнить это (с помощью shlex
или иначе )?
РЕДАКТИРОВАТЬ:
Если это поможет, вот синтаксис команды CHANGE
, приведенный в файле справки :
'''
C [/stg1/stg2/ [n|n m]]
The CHANGE command replaces the m-th occurrence of "stg1" with "stg2"
for the next n lines. The default value for m and n is 1.'''
. Столь же сложные для токенизации команды X
и Y
:
'''
X [/command/[command/[...]]n]
Y [/command/[command/[...]]n]
The X and Y commands allow the execution of several commands contained
in one command. To define an X or Y "command string", enter X (or Y)
followed by a space, then individual commands, each separated by a
delimiter (e.g. a period "."). An unlimited number of commands may be
placed in the X or Y command string. Once the command string has been
defined, entering X (or Y) followed optionally by a count n will execute
the defined command string n times. If n is not specified, it will
default to 1.'''