Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add 'directly head/tail recursion' optimized syntax '+' #40

Merged
merged 2 commits into from
Jan 8, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions grammars/f1_g4_translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,30 @@ def esc_token(self, t):
t = t.replace('\t', '\\t')
return t

def rule_to_s(self, rule, grammar):
return ' '.join(["'%s'" % self.esc_token(t)
def rule_to_s(self, key, rule, grammar):
# feat: add 'directly head/tail recursion' optimized syntax '+'
if len(rule) == 0:
return ''

# head recursion
recursion = False
if rule[0] == key:
rule = rule[1:]
recursion = True
# tail recursion
if rule[-1] == key:
rule = rule[:-1]
recursion = True

# append rules
data = ' '.join(["'%s'" % self.esc_token(t)
if t not in grammar else self.to_key(t)
for t in rule])

if recursion:
data = "(%s)+" % data
return data

def translate(self):
lines = ['grammar Grammar;']
entries = '\n | '.join([self.to_key(entry_k) + ' EOF' for entry_k in self.entry_keys])
Expand All @@ -89,7 +108,7 @@ def translate(self):
;''' % entries)
for k in self.grammar_keys:
rules = self.grammar[k]
v = '\n | '.join([self.rule_to_s(rule, self.grammar)
v = '\n | '.join([self.rule_to_s(key, rule, self.grammar)
h1994st marked this conversation as resolved.
Show resolved Hide resolved
for rule in rules])
lines.append('''\
%s
Expand Down
Loading