Skip to content

Instantly share code, notes, and snippets.

@Heimdell
Last active October 21, 2018 17:33
Show Gist options
  • Save Heimdell/60c0d9ef46bea8956143acf927d20f5b to your computer and use it in GitHub Desktop.
Save Heimdell/60c0d9ef46bea8956143acf927d20f5b to your computer and use it in GitHub Desktop.
parseOp(Soup, Operator)
:- append([Operator], Pattern)
, append(Pattern, Soup)
.
opTable(Table) :-
Table =
[ [Whole, [<], Index, [>]] -> index(left, Whole, Index)
, [[if], Bool, [then], Yes, [else], No] -> if_then_else_(right, Bool, Yes, No)
, [X, [=], Y] -> =(open, X, Y)
, [X, [is, not], Y] -> is_not(open, X, Y)
, [['('], X, [')']] -> the(closed, X)
, [[T]] -> terminal(term, T)
]
.
arithTable(Table) :-
Table =
[ [A, [+], B] -> +(open, A, B)
, [A, [-], B] -> -(open, A, B)
, [A, [*], B] -> *(open, A, B)
, [A, [/], B] -> /(open, A, B)
, [A, [^], B] -> ^(open, A, B)
, [['('], X, [')']] -> identity(closed, X)
, [[T]] -> terminal(term, T)
]
.
parse(Global, Soup, Result) :- parse(o, Global, Global, Soup, Result).
parse(Level, [Rule | Rest], Global, Soup, Result)
:- copy_term(Rule, Op -> Prod)
, log(Level, is_it(Soup, Op))
, parseOp(Soup, Op)
, Prod =.. [Name, Assoc | Args]
, ( Assoc = right
-> append(Restarted, [Last], Args)
, maplist(parse(s(Level), Global, Global), Restarted, Center)
, parse(s(Level), Rest, Global, Last, LastArg)
, append(Center, [LastArg], ResultArgs)
, Result =.. [Name | ResultArgs]
; Assoc = left
-> append([First], Restarted, Args)
, maplist(parse(s(Level), Global, Global), Restarted, Center)
, parse(s(Level), Rest, Global, First, FirstArg)
, append([FirstArg], Center, ResultArgs)
, Result =.. [Name | ResultArgs]
; Assoc = closed
-> maplist(parse(s(Level), Global, Global), Args, ResultArgs)
, Result =.. [Name | ResultArgs]
; Assoc = open
-> append([[First], Restarted, [Last]], Args)
, maplist(parse(s(Level), Global, Global), Restarted, Center)
, maplist(parse(s(Level), Rest, Global), [First, Last], [FirstArg, LastArg])
, append([[FirstArg], Center, [LastArg]], ResultArgs)
, Result =.. [Name | ResultArgs]
; Assoc = term
, [Result] = Args
, \+ member(Result, [if, then, else, =, <, >, '(', ')', is, not])
)
.
parse(Level, [_ | Rest], Global, Soup, Result)
:- parse(Level, Rest, Global, Soup, Result)
.
log(o, Msg) :- writeln(Msg).
log(s(R), Msg) :- write(' '), log(R, Msg).
?- opTable(T)
, Source = [if, if, '(', x, <, i, >, ')', =, y, is, not, true, then, x, else, y, then, x, else, y]
, parse(T, Source, AST)
, writeln('')
, writeln(Source)
, writeln(' ->')
, writeln(AST)
.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment