我必须用Prolog和C ++制作词法分析器。我的C ++中的词法分析器正在运行,但是我的序言代码有一些问题。我无法识别关键字
这是我的序言代码,其中不包含有效的关键字\
predicates
string_processing
det_lexical_atom_type(char)
is_identif(char)
is_op(char)
is_delim(char)
is_const(char)
p1(string)
clauses
string_processing:-write("Write the expression"),nl,readln(S),p1(S).
p1(S):-frontchar(S,C,R),det_lexical_atom_type(C),p1(R).
p1("#"):-!.
det_lexical_atom_type(C):-is_identif(C),write("\n Is identif",C).
det_lexical_atom_type(C):-is_op(C),write("\n is op",C).
det_lexical_atom_type(C):-is_delim(C),write("\n is delim",C).
det_lexical_atom_type(C):-is_const(C),write("\n is const",C).
det_lexical_atom_type(C):-write("\n Unknown lexical atom").
is_identif(C):-C='A'.
is_op(C):-C='+';C='*'.
is_delim(C):-C='(';C=')'.
is_const(C):-C='0';C='1'.
这是我的序言代码,经过修改可以识别关键字,但是不起作用。该程序停止读取我在第一个字母后立即给出的表达式,并且无法继续识别其余的表达式。例如我输入T = 3 + a,它只读取T,然后停止
predicates
string_processing
is_identif(char)
is_op(char)
is_delim(char)
is_const(char)
is_keyword(string)
p2(string)
determine_lexical_atom_type(char)
determine_keyword(string)
clauses
is_identif(C):-C='A';C='B';C='C';C='D'.
is_op(C):-C='+';C='-';C='/';C='*';C='='.
is_delim(C):-C=';';C=',';C='(';C=')'.
is_const(C):-C='0';C='1';C='2';C='3';C='4';C='5';C='6';C='7';C='8';C='9'.
is_keyword(T):-T="if";T="while";T="do";T="switch";T="for";
T="break";T="until";T="then".
determine_keyword(T):-is_keyword(T),write("\nIs keyword: ",T).
determine_lexical_atom_type(C):-is_identif(C),write("\nIs identif:",C).
determine_lexical_atom_type(C):-is_op(C),write("\nIs operator: ",C).
determine_lexical_atom_type(C):-is_delim(C),write("\nIs delimiter: ",C).
determine_lexical_atom_type(C):-is_const(C),write("\n Is constant ",C).
determine_lexical_atom_type(C):-write("\n Unknown lexical atom").
p2(S):- fronttoken(S,T,R),write("\nT=",T),determine_keyword(T),frontchar(R,C,R1),determine_lexical_atom_type(C),p2(R1).
p2("#"):-!.
string_processing:-write("Write expression"),nl,readln(S),p2(S),nl.
答案 0 :(得分:0)
问题很简单:
只需将determine_keyword/1
移到fronttoken/3
之前,下面是代码片段。完成此操作后,关键字识别应该会起作用。
p2(S):-
determine_keyword(T), //output var
fronttoken(S,T,R),
write("\nT=",T),
frontchar(R,C,R1),
determine_lexical_atom_type(C),
fail.
p2(_).
determine_keyword/1
生成回溯时所有关键字的列表