Skip to content

Commit 9082537

Browse files
committed
Add a human friendly grammar.
1 parent 8d5baa9 commit 9082537

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

g4/Ds.g4

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
grammar Ds;
2+
3+
rule_pool
4+
: rule (NEWLINE+ rule)* EOF
5+
;
6+
7+
rule
8+
: term
9+
| (term (',' term)*)? '->' term
10+
;
11+
12+
term
13+
: SYMBOL # symbol
14+
| term '(' (term (',' term)*)? ')' # function
15+
| '(' term ')' # parentheses
16+
| <assoc=right> ('~' | '!' | '-' | '+' | '&' | '*') term # unary
17+
| term ('*' | '/' | '%') term # binary
18+
| term ('+' | '-') term # binary
19+
| term ('<<' | '>>') term # binary
20+
| term ('<' | '>' | '<=' | '>=') term # binary
21+
| term ('==' | '!=') term # binary
22+
| term '&' term # binary
23+
| term '^' term # binary
24+
| term '|' term # binary
25+
| term '&&' term # binary
26+
| term '||' term # binary
27+
;
28+
29+
WHITESPACE
30+
: [ \t]+ -> skip
31+
;
32+
33+
COMMENT
34+
: '//' ~[\r\n]* -> skip
35+
;
36+
37+
NEWLINE
38+
: [\r\n]
39+
;
40+
41+
SYMBOL
42+
: ~[ \t\r\n,()]+
43+
;

g4/main.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from antlr4 import FileStream, CommonTokenStream
2+
from DsLexer import DsLexer
3+
from DsParser import DsParser
4+
from DsVisitor import DsVisitor
5+
6+
7+
class Visitor(DsVisitor):
8+
def visitRule_pool(self, ctx: DsParser.Rule_poolContext):
9+
return "\n\n".join([self.visit(r) for r in ctx.rule_()])
10+
11+
def visitRule(self, ctx: DsParser.RuleContext):
12+
result = [self.visit(t) for t in ctx.term()]
13+
if len(result) == 1:
14+
return result[0]
15+
else:
16+
conclusion = result.pop()
17+
length = max(len(premise) for premise in result)
18+
result.append("-" * length)
19+
result.append(conclusion)
20+
return "\n".join(result)
21+
22+
def visitSymbol(self, ctx: DsParser.SymbolContext):
23+
return ctx.SYMBOL().getText()
24+
25+
def visitFunction(self, ctx: DsParser.FunctionContext):
26+
return f"(function {' '.join(self.visit(t) for t in ctx.term())})"
27+
28+
def visitParentheses(self, ctx: DsParser.ParenthesesContext):
29+
return self.visit(ctx.term())
30+
31+
def visitUnary(self, ctx: DsParser.UnaryContext):
32+
return f"(unary {ctx.getChild(0).getText()} {self.visit(ctx.term())})"
33+
34+
def visitBinary(self, ctx: DsParser.BinaryContext):
35+
return f"(binary {ctx.getChild(1).getText()} {self.visit(ctx.term(0))} {self.visit(ctx.term(1))})"
36+
37+
38+
input_stream = FileStream("input.ds")
39+
lexer = DsLexer(input_stream)
40+
stream = CommonTokenStream(lexer)
41+
parser = DsParser(stream)
42+
tree = parser.rule_pool()
43+
visitor = Visitor()
44+
result = visitor.visit(tree)
45+
print(result)

0 commit comments

Comments
 (0)