1
1
mirror of https://github.com/kanaka/mal.git synced 2024-11-11 00:52:44 +03:00
mal/matlab/reader.m

82 lines
2.7 KiB
Mathematica
Raw Normal View History

2015-02-08 05:32:06 +03:00
% this is just being used as a namespace
classdef reader
methods (Static = true)
function tokens = tokenize(str)
re = '[\s,]*(~@|[\[\]{}()''`~^@]|"(?:\\.|[^\\"])*"|;.*|[^\s\[\]{}(''"`,;)]*)';
% extract the capture group (to ignore spaces and commas)
tokens = cellfun(@(x) x(1), regexp(str, re, 'tokens'));
end
function atm = read_atom(rdr)
token = rdr.next();
%fprintf('in read_atom: %s\n', token);
if not(isempty(regexp(token, '^-?[0-9]+$', 'match')))
atm = str2double(token);
elseif strcmp(token(1), '"')
atm = token(2:length(token)-1);
2015-02-08 22:18:08 +03:00
atm = strrep(atm, '\"', '"');
atm = strrep(atm, '\n', char(10));
2015-02-08 10:13:41 +03:00
elseif strcmp(token, 'nil')
atm = types.nil;
2015-02-08 05:32:06 +03:00
elseif strcmp(token, 'true')
atm = true;
elseif strcmp(token, 'false')
atm = false;
else
atm = types.Symbol(token);
end
end
function lst = read_list(rdr)
%fprintf('in read_list\n');
lst = {};
token = rdr.next();
if not(strcmp(token, '('))
error('expected ''(''');
end
token = rdr.peek();
while true
if eq(token, false)
error('expected '')''');
end
if strcmp(token, ')'), break, end
lst{length(lst)+1} = reader.read_form(rdr);
token = rdr.peek();
end
rdr.next();
end
function ast = read_form(rdr)
%fprintf('in read_form\n');
token = rdr.peek();
2015-02-09 04:23:49 +03:00
switch token
case ''''
rdr.next();
ast = {types.Symbol('quote'), reader.read_form(rdr)};
case '`'
rdr.next();
ast = {types.Symbol('quasiquote'), reader.read_form(rdr)};
case '~'
rdr.next();
ast = {types.Symbol('unquote'), reader.read_form(rdr)};
case '~@'
rdr.next();
ast = {types.Symbol('splice-unquote'), reader.read_form(rdr)};
2015-02-08 05:32:06 +03:00
case ')'
error('unexpected '')''');
case '('
ast = reader.read_list(rdr);
otherwise
ast = reader.read_atom(rdr);
end
end
function ast = read_str(str)
%fprintf('in read_str\n');
tokens = reader.tokenize(str);
rdr = Reader(tokens);
ast = reader.read_form(rdr);
end
end
end