Hi I'm trying to build a parser in python that parses siemens cnc for a project and i have got it to detect some syntax errors but others it just ignores
this is my code: from pyparsing import Word, alphas, nums, Suppress, Group, LineEnd, OneOrMore, restOfLine, ZeroOrMore, ParseException
integer = Word(nums).setParseAction(lambda t: int(t[0]))
float_number = Word(nums + ".").setParseAction(lambda t: float(t[0]))
identifier = Word(alphas, alphas + nums + "_")
input_text = """
G95 X10 Y20
G02 X30 Y40 I5 J5
G0 Z5
;comment
M03
G01 X15 Y25 H10
;comment here too
"""
g_code = (Suppress("G") + integer).setParseAction(lambda t: f"G{t[0]:02d}")
m_code = (Suppress("M") + integer).setParseAction(lambda t: f"M{t[0]:02d}")
x_coordinate = Group("X" + float_number)
y_coordinate = Group("Y" + float_number)
z_coordinate = Group("Z" + float_number)
i_coordinate = Group("I" + float_number)
j_coordinate = Group("J" + float_number)
code = (g_code | m_code) + ZeroOrMore(x_coordinate | y_coordinate | z_coordinate | i_coordinate | j_coordinate)("params") + restOfLine
comment = Suppress(";" + restOfLine)
siemens_cnc_grammar = OneOrMore(Group(code | comment))
try:
parsed_result = siemens_cnc_grammar.parseString(input_text, parseAll=True)
for line in parsed_result:
if len(line) > 0 and line[0] != ";":
command = line[0]
print("Command:", command)
for param_value in line.params:
param_key = param_value[0]
param_val = param_value[1]
print("Parameter:", param_key, "=", param_val)
print()
except ParseException as e:
print("Syntax Error:")
print("Line:", e.lineno)
print("Context:", e.markInputline())
the H10 is an example syntax error I added to test it but it just ignores it and doesn't pick up on it. i tried using chatgpt/some ai for help as im very new to building the parser but it just made everything worse