Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import re
- def check_chunk_bounds(chunks,m):
- #try:
- if chunks[0][0] in m.keys():
- end,close,escape = 0,m[chunks[0][0]],"\\"
- trim_chars = "".join(set(close + chunks[0][0]))
- while (chunks[end][-1]!=close and chunks[end][-2]!=escape):end+=1
- end=end+1 if end+1<len(chunks) else None
- chunk=("".join(chunks[:end])).strip(trim_chars)
- print(chunk)
- return chunk,(chunks[end:] if end else [])
- #except IndexError as e:print(e)
- #finally:return None,chunks
- return None,chunks
- class ChunkBase(object):
- prefix='@'
- def __init__(self,v):self.val = v
- def __str__(self):return self.prefix+self.val
- class RegexChunk(ChunkBase):
- prefix='regex:'
- class OtherChunk(ChunkBase):
- prefix='value:'
- class Rule:
- def __init__(self,spec):
- chunks,spec=spec.split(),[]
- types={
- RegexChunk:{'"':'"',"'":"'"},
- OtherChunk:{'[':']','{':'}','(':')','<':'>'}
- }
- while len(chunks)>0:
- progressed=False
- for chunk_type,chunk_closures in types.items():
- chunk,chunks = check_chunk_bounds(chunks,chunk_closures)
- if chunk is not None:
- spec.append(chunk_type(chunk))
- progressed=True
- break
- if not progressed:
- spec.append(ChunkBase(chunks[0]))
- chunks=chunks[1:]
- self.chunks=spec
- class Grammar:
- def __init__(self,ospec):
- #Ignore comments.
- rule_specs="\n".join([rs[:rs.find("//")].strip() for rs in ospec.split("\n")])
- rule_specs=[rs.strip() for rs in rule_specs.split(";") if len(rs.strip())>0]
- rules={}
- for spec in rule_specs:
- ind = spec.find(":")
- if ind<0:
- raise LogicError("Missing ':' identifier.")
- name = spec[:ind].strip()
- if any([(c in " \n\t") for c in name]):
- raise LogicError("Grammar Rule can't have white-space in its name.")
- rule = spec[ind+1:].strip()
- rules[name]=Rule(rule)
- self.rules=rules
- g=Grammar(r"""
- number: 'AHA\' HAH';// CAWMENTS. CAWMENTS ERRYWHER.
- KA_DURP: DZ:RLKJAF;//wuthaha
- """)
- for name,rule in g.rules.items():
- print(name,":",*[chunk for chunk in rule.chunks])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement