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

Parsing of characters #75

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
230 changes: 179 additions & 51 deletions src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,35 @@
//! not; since this is about being a 'free-er' Clojure, especially since it can't compete with it in raw
//! power, neither speed or ecosystem, it might be worth it to leave in reader macros.

use nom::combinator::{verify};
use nom::combinator::verify;
use nom::{
branch::alt, bytes::complete::tag, combinator::opt, map, sequence::preceded, take_until,
Err::Incomplete, IResult
Err::Incomplete, IResult,
};

use crate::error_message;
use crate::keyword::Keyword;
use crate::maps::MapEntry;
use crate::persistent_list::ToPersistentList;
use crate::persistent_list_map::{PersistentListMap,ToPersistentListMap, ToPersistentListMapIter};
use crate::persistent_list_map::{PersistentListMap, ToPersistentListMap, ToPersistentListMapIter};
use crate::persistent_vector::ToPersistentVector;
use crate::protocol::ProtocolCastable;
use crate::protocol::Protocol;
use crate::symbol::Symbol;
use crate::error_message;
use crate::value::{ToValue, Value};
use std::rc::Rc;
use crate::protocol::ProtocolCastable;
use crate::protocols;
use crate::symbol::Symbol;
use crate::traits::IObj;
use crate::value::{ToValue, Value};
use crate::traits::IMeta;
use std::io::BufRead;
use std::rc::Rc;
//
// Note; the difference between ours 'parsers'
// identifier_parser
// symbol_parser
// integer_parser
// And our 'try readers'
// try_read_i32
// try_read_char
// try_read_string
// try_read_map
// try_read_list
Expand Down Expand Up @@ -288,10 +289,10 @@ pub fn identifier_parser(input: &str) -> IResult<&str, String> {
/// namespace.subnamespace/a cat/b a.b.c/|ab123|
pub fn symbol_parser(input: &str) -> IResult<&str, Symbol> {
named!(namespace_parser <&str,String>,
do_parse!(
ns: identifier_parser >>
complete!(tag!("/")) >>
(ns)));
do_parse!(
ns: identifier_parser >>
complete!(tag!("/")) >>
(ns)));

let (rest_input, ns) = opt(namespace_parser)(input)?;
let (rest_input, name) = identifier_parser(rest_input)?;
Expand Down Expand Up @@ -466,6 +467,52 @@ pub fn try_read_nil(input: &str) -> IResult<&str, Value> {
Ok((rest_input, Value::Nil))
}

/// Tries to parse &str into Value::Char
/// Example Successes:
/// "\newline" => Value::Char("\n")
/// Example Failures:
///
pub fn try_read_char(input: &str) -> IResult<&str, Value> {
named!(backslash<&str, &str>, preceded!(consume_clojure_whitespaces_parser, tag!("\\")));

fn str_to_unicode(s: &str) -> char {
u32::from_str_radix(s, 16)
.ok()
.and_then(std::char::from_u32)
.unwrap()
}

named!(unicode < &str, char>, alt!(
preceded!(
tag!("u"),
alt!(
map!(take_while_m_n!(4,4, |c :char| c.is_digit(16)), str_to_unicode)
)
)
));

named!(special_escapes < &str, char>, complete!( alt!(
tag!("newline") => { |_| '\n'} |
tag!("space") => { |_| ' ' } |
tag!("tab") => { |_| '\t'} |
//tag!("formfeed") => { |_| '\f'} |
//tag!("backspace") => { |_| '\b'} |
tag!("return") => { |_| '\r' } )));

named!(normal_char < &str, char>,
// accept anything after \
map!(take_while_m_n!(1,1,|_| true), first_char));

named!(char_parser<&str,char>,
alt!(unicode | special_escapes | normal_char));

let (rest_input, _) = backslash(input)?;

let (rest_input, char_value) = char_parser(rest_input)?;

Ok((rest_input, Value::Char(char_value)))
}

// @TODO allow escaped strings
/// Tries to parse &str into Value::String
/// Example Successes:
Expand All @@ -492,7 +539,7 @@ pub fn try_read_var(input: &str) -> IResult<&str, Value> {
let (rest_input, val) = try_read(rest_input)?;
// #'x just expands to (var x), just like 'x is just a shorthand for (quote x)
// So here we return (var val)
Ok((rest_input,list_val!(sym!("var") val)))
Ok((rest_input, list_val!(sym!("var") val)))
}

// @TODO Perhaps generalize this, or even generalize it as a reader macro
Expand Down Expand Up @@ -524,40 +571,46 @@ pub fn try_read_meta(input: &str) -> IResult<&str, Value> {
named!(meta_start<&str, &str>, preceded!(consume_clojure_whitespaces_parser, tag!("^")));
let (rest_input, _) = meta_start(input)?;

let (rest_input,meta_value) = try_read(rest_input)?;
let (rest_input, meta_value) = try_read(rest_input)?;
let mut meta = PersistentListMap::Empty;
match &meta_value {
Value::Symbol(symbol) => {
// @TODO Note; do NOT hardcode this, make some global for TAG_KEY, like Clojure does
meta = persistent_list_map!{"tag" => symbol};
},
meta = persistent_list_map! {"tag" => symbol};
}
Value::Keyword(keyword) => {
meta = persistent_list_map!(
MapEntry {
key: meta_value.to_rc_value(),
val: true.to_rc_value()
}
);
},
meta = persistent_list_map!(MapEntry {
key: meta_value.to_rc_value(),
val: true.to_rc_value()
});
}
Value::String(string) => {
// @TODO Note; do NOT hardcode this, make some global for TAG_KEY, like Clojure does
meta = persistent_list_map!{"tag" => string};
},
meta = persistent_list_map! {"tag" => string};
}
Value::PersistentListMap(plist_map) => {
meta = plist_map.clone();
// Then we're already set
// Then we're already set
}
_ => {
// @TODO check instanceof IPersistentMap here instead
// @TODO Clojure has basically this one off error here, but another thing we wish to do
// is write clear errors
return Ok((rest_input,error_message::custom("When trying to read meta: metadata must be Symbol, Keyword, String, or Map")))
// is write clear errors
return Ok((
rest_input,
error_message::custom(
"When trying to read meta: metadata must be Symbol, Keyword, String, or Map",
),
));
}
}
let (rest_input,iobj_value) = try_read(rest_input)?;
let (rest_input, iobj_value) = try_read(rest_input)?;

// Extra clone, implement these functions for plain Values
if let Some(iobj_value) = iobj_value.to_rc_value().try_as_protocol::<protocols::IObj>() {
// Extra clone, implement these functions for plain Values
if let Some(iobj_value) = iobj_value
.to_rc_value()
.try_as_protocol::<protocols::IObj>()
{
// @TODO get actual line and column info
let line = 1;
let column = 1;
Expand Down Expand Up @@ -638,6 +691,7 @@ pub fn try_read(input: &str) -> IResult<&str, Value> {
try_read_quoted,
try_read_nil,
try_read_map,
try_read_char,
try_read_string,
try_read_f64,
try_read_i32,
Expand Down Expand Up @@ -869,6 +923,47 @@ mod tests {
}
}

mod try_read_char_tests {
use crate::reader::try_read_char;
use crate::value::Value;

// #[test]
// fn try_read_char_test() {
// assert_eq!(Value::Char("\\f"), try_read_char("\\formfeed"))
// }

#[test]
fn try_read_char_space() {
assert_eq!(Value::Char(' '), try_read_char("\\space").ok().unwrap().1);
}

#[test]
fn try_read_char_return() {
assert_eq!(Value::Char('\r'), try_read_char("\\return").ok().unwrap().1);
}

#[test]
fn try_read_char_hashtag() {
assert_eq!(Value::Char('#'), try_read_char("\\#").ok().unwrap().1);
}
#[test]
fn try_read_char_n() {
assert_eq!(Value::Char('n'), try_read_char("\\n").ok().unwrap().1);
}
#[test]
fn try_read_char_f() {
assert_eq!(Value::Char('r'), try_read_char("\\r").ok().unwrap().1);
}
#[test]
fn try_read_unicode() {
assert_eq!(Value::Char('张'), try_read_char("\\u5F20").ok().unwrap().1);
}
#[test]
fn try_read_char_fail() {
assert!(try_read_char("d").is_err());
}
}

mod try_read_symbol_tests {
use crate::reader::try_read_symbol;
use crate::symbol::Symbol;
Expand All @@ -883,16 +978,31 @@ mod tests {
}
}

// mod try_read_char_tests {
// use crate::reader::try_read_char;
// use crate::value::Value;
//
// #[test]
// fn try_read_char_test() {
// assert_eq!(Value::Char('f'), try_read_character("\\f"))
// }
//
// #[test]
// fn try_read_newline_test() {
// assert_eq!(Value::Char('\n'), try_read_character("\newline"))
// }
// }

mod try_read_tests {
use crate::keyword::Keyword;
use crate::persistent_list;
use crate::persistent_list_map;
use crate::persistent_list_map::IPersistentMap;
use crate::keyword::Keyword;
use crate::persistent_vector;
use crate::reader::try_read;
use crate::symbol::Symbol;
use crate::value::{ToValue,Value};
use crate::value::Value::{PersistentList, PersistentListMap, PersistentVector};
use crate::value::{ToValue, Value};

#[test]
fn try_read_empty_map_test() {
Expand Down Expand Up @@ -1000,45 +1110,61 @@ mod tests {
}
#[test]
fn try_read_meta_symbol() {
let with_meta = "^cat a";
let with_meta = "^cat a";
match try_read(with_meta).ok().unwrap().1 {
Value::Symbol(symbol) => {
assert!(symbol.meta().contains_key(&Keyword::intern("tag").to_rc_value()));
assert!(symbol
.meta()
.contains_key(&Keyword::intern("tag").to_rc_value()));
assert_eq!(
Symbol::intern("cat").to_value(),
*symbol.meta().get(&Keyword::intern("tag").to_rc_value())
);
},
_ => panic!("try_read_meta \"^cat a\" should return a symbol")
}
_ => panic!("try_read_meta \"^cat a\" should return a symbol"),
}
}
#[test]
fn try_read_meta_string() {
let with_meta = "^\"cat\" a";
match try_read(with_meta).ok().unwrap().1 {
Value::Symbol(symbol) => {
assert_eq!(String::from("a"),symbol.name);
assert!(symbol.meta().contains_key(&Keyword::intern("tag").to_rc_value()));
assert_eq!(String::from("a"), symbol.name);
assert!(symbol
.meta()
.contains_key(&Keyword::intern("tag").to_rc_value()));
assert_eq!(
"cat".to_value(),
*symbol.meta().get(&Keyword::intern("tag").to_rc_value())
);
},
_ => panic!("try_read_meta '^\"cat\" a' should return a symbol")
}
_ => panic!("try_read_meta '^\"cat\" a' should return a symbol"),
}
}
#[test]
fn try_read_meta_persistent_list_map() {
let with_meta = "^{:cat 1 :dog 2} a";
match try_read(with_meta).ok().unwrap().1 {
Value::Symbol(symbol) => {
assert!(symbol.meta().contains_key(&Keyword::intern("cat").to_rc_value()));
assert_eq!(Value::I32(1),*symbol.meta().get(&Keyword::intern("cat").to_rc_value()));
assert!(symbol.meta().contains_key(&Keyword::intern("dog").to_rc_value()));
assert_eq!(Value::I32(2),*symbol.meta().get(&Keyword::intern("dog").to_rc_value()));
assert!(!symbol.meta().contains_key(&Keyword::intern("chicken").to_rc_value()));
},
_ => panic!("try_read_meta \"^{:cat 1 :dog 2} a\" should return a symbol")
assert!(symbol
.meta()
.contains_key(&Keyword::intern("cat").to_rc_value()));
assert_eq!(
Value::I32(1),
*symbol.meta().get(&Keyword::intern("cat").to_rc_value())
);
assert!(symbol
.meta()
.contains_key(&Keyword::intern("dog").to_rc_value()));
assert_eq!(
Value::I32(2),
*symbol.meta().get(&Keyword::intern("dog").to_rc_value())
);
assert!(!symbol
.meta()
.contains_key(&Keyword::intern("chicken").to_rc_value()));
}
_ => panic!("try_read_meta \"^{:cat 1 :dog 2} a\" should return a symbol"),
}
}
#[test]
Expand All @@ -1057,9 +1183,11 @@ mod tests {
let with_meta = "^:cat a";
match try_read(with_meta).ok().unwrap().1 {
Value::Symbol(symbol) => {
assert!(symbol.meta().contains_key(&Keyword::intern("cat").to_rc_value()));
},
_ => panic!("try_read_meta \"^:cat a\" should return a symbol")
assert!(symbol
.meta()
.contains_key(&Keyword::intern("cat").to_rc_value()));
}
_ => panic!("try_read_meta \"^:cat a\" should return a symbol"),
}
}
#[test]
Expand Down
4 changes: 3 additions & 1 deletion src/type_tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub enum TypeTag {
Boolean,
Symbol,
Var,
Char,
Keyword,
IFn,
Condition,
Expand All @@ -28,10 +29,11 @@ impl fmt::Display for TypeTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match self {
I32 => std::string::String::from("rust.std.i32"),
Boolean => std::string::String::from("rust.std.bool"),
F64 => std::string::String::from("rust.std.f64"),
Boolean => std::string::String::from("rust.std.bool"),
Symbol => std::string::String::from("clojure.lang.Symbol"),
Var => std::string::String::from("clojure.lang.Var"),
Char => std::string::String::from("clojure.lang.Char"),
Keyword => std::string::String::from("clojure.lang.Keyword"),
IFn => std::string::String::from("clojure.lang.Function"),
Condition => std::string::String::from("clojure.lang.Condition"),
Expand Down
Loading