Commits

Seth Hobson  committed dd556c0

completed Wren lexer and other Prolog programs

  • Participants
  • Parent commits 4127279

Comments (0)

Files changed (2)

File Prolog/sampleprog.wren

+program gcd is
+	var m,n : integer;
+begin
+	read m; read n; 
+	while m <> n do
+		if m < n then n:= n - m
+			else m := m - n
+		end if
+	end while;
+	write m
+end

File Prolog/wren.pl

+%% Wren lexer
+%% author: Seth Hobson
+
+wrenLex(Tokens) :- nl,
+  write('>>> Lexical Analyzer for Wren <<<'), nl,
+  write('Enter name of source file: '), nl,
+  getfilename(FileName), nl,
+  see(FileName), scan(Tokens), seen,
+  write('Scan successful').
+
+getfilename(F) :- get0(C), restfilename(C, Cs), atom_codes(F, Cs).
+
+restfilename(C, []) :- \+(filechar(C)).
+restfilename(C, [C|Cs]) :- filechar(C), get0(D), restfilename(D, Cs).
+
+filechar(C) :- lower(C) ; upper(C) ; digit(C) ; period(C) ; slash(C).
+
+lower(Char) :- 97 =< Char, Char =< 122.
+upper(Char) :- 65 =< Char, Char =< 90.
+digit(Char) :- 48 =< Char, Char =< 57.
+period(46).
+slash(47).
+
+scan([T|Ts]) :- get0(Ci), gettoken(Ci, T, Co), restprog(T, Co, Ts).
+
+idchar(Char) :- lower(Char) ; digit(Char).
+
+resword(program).
+resword(is).
+resword(begin).
+resword(write).
+resword(read).
+resword(do).
+resword(if).
+resword(else).
+resword(true).
+resword(false).
+resword(boolean).
+resword(integer).
+resword(then).
+resword(var).
+resword(while).
+resword(done).
+
+single(40, lparen).
+single(41, rparen).
+single(42, times).
+single(43, plus).
+single(44, comma).
+single(45, minus).
+single(47, divide).
+single(59, semicolon).
+single(61, equal).
+
+double(58, colon).
+double(60, less).
+double(62, grtr).
+
+pair(58, 61, assign).
+pair(60, 62, neq).
+pair(62, 61, gteq).
+pair(60, 61, lteq).
+pair(58, 32, colon).
+pair(62, 32, grtr).
+pair(60, 32, less).
+
+space(32).
+tabch(9).
+endline(10).
+
+whitespace(Char) :- space(Char) ; tabch(Char) ; endline(Char).
+
+endfile(26).
+endfile(-1).
+
+gettoken(C, eop, 0) :- endfile(C).
+gettoken(Ci, T, Co) :- whitespace(Ci), get0(C), gettoken(C, T, Co).
+gettoken(Ci, T, Co) :- single(Ci, T), get0(Co).
+gettoken(Ci, To, Co) :- double(Ci, Ti), get0(C), buildpair(Ci, C, Co, Ti, To).
+gettoken(Ci, To, Co) :- lower(Ci), restid(Ci, Lc, Co), atom_codes(Ti, Lc), buildid(Ti, To).
+gettoken(C, _, _) :- write('Illegal character: '), put(C), nl, abort.
+
+buildpair(C1i, C2i, Co, _, To) :- pair(C1i, C2i, To), get0(Co).
+buildpair(C1i, C2i, Co, _, To) :- \+pair(C1i, C2i, To), single(Co, To).
+
+restid(C, [], C) :- \+(idchar(C)).
+restid(C, [C|List], Co) :- idchar(C), get0(Ci), restid(Ci, List, Co).
+
+buildid(Ti, To) :- \+resword(Ti), To = ide(Ti).
+buildid(Ti, To) :- resword(Ti), To = resword(Ti).
+
+restprog(eop, _, []). % end of file in previous character
+restprog(_, Ci, [T|Lt]) :- gettoken(Ci, T, Co), restprog(T, Co, Lt).