summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGreg Brown <gmb60@cam.ac.uk>2021-01-07 12:44:06 +0000
committerGreg Brown <gmb60@cam.ac.uk>2021-01-07 12:44:06 +0000
commitfe2eac31d9dbec772796c3ea75be32e9cd01b810 (patch)
treead0c0ad42ce986d3dd915512de8c18968194c15a
parenteb280a903f8f20d0b0c0ef5acae955a20929d100 (diff)
Add first steps of AutoChomp
-rw-r--r--Cargo.toml11
-rw-r--r--autochomp/Cargo.toml15
-rw-r--r--autochomp/build.rs73
-rw-r--r--autochomp/src/main.rs23
-rw-r--r--autochomp/src/nibble.nb67
-rw-r--r--chewed/src/error.rs4
-rw-r--r--chewed/src/parse.rs8
-rw-r--r--examples/autochomp/main.rs3
-rw-r--r--src/chomp/error.rs2
-rw-r--r--src/lower/rust.rs7
10 files changed, 199 insertions, 14 deletions
diff --git a/Cargo.toml b/Cargo.toml
index f25ec0c..ca41e36 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,18 +5,15 @@ authors = ["Greg Brown <gmb60@cam.ac.uk>"]
edition = "2018"
[workspace]
-members = ["chewed"]
+members = ["autochomp", "chewed"]
[dependencies]
-quote = "1.0.7"
+quote = "1"
[dependencies.proc-macro2]
-version = "1.0.24"
+version = "1"
features = ["span-locations"]
[dependencies.syn]
-version = "1.0.48"
+version = "1"
features = ["extra-traits"]
-
-[dev-dependencies]
-chewed = {path = "chewed"}
diff --git a/autochomp/Cargo.toml b/autochomp/Cargo.toml
new file mode 100644
index 0000000..4e20c49
--- /dev/null
+++ b/autochomp/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "autochomp"
+version = "0.1.0"
+authors = ["Greg Brown <gmb60@cam.ac.uk>"]
+edition = "2018"
+
+[build-dependencies]
+chomp = {path = ".."}
+
+[build-dependencies.syn]
+version = "1"
+features = ["extra-traits"]
+
+[dependencies]
+chewed = {path = "../chewed"}
diff --git a/autochomp/build.rs b/autochomp/build.rs
new file mode 100644
index 0000000..952d49c
--- /dev/null
+++ b/autochomp/build.rs
@@ -0,0 +1,73 @@
+use std::{
+ env,
+ error::Error,
+ fmt::Display,
+ fs,
+ io::{Read, Write},
+ path::Path,
+ process::exit,
+};
+
+use chomp::{
+ chomp::{
+ check::{InlineCall, TypeCheck},
+ context::Context,
+ visit::Visitable,
+ },
+ lower::{rust::RustBackend, Backend, GenerateCode},
+ nibble::cst::File,
+};
+
+const PATH: &str = "src/nibble.nb";
+
+#[derive(Debug)]
+struct UndecVar;
+
+impl Display for UndecVar {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Undeclared variable somewhere.")
+ }
+}
+impl Error for UndecVar {}
+
+fn main() {
+ println!("cargo:rerun-if-changed={}", PATH);
+
+ let out_dir = env::var("OUT_DIR").unwrap();
+
+ let mut input = String::new();
+ let res = fs::File::open(PATH)
+ .map_err(|e| Box::new(e) as Box<dyn Error>)
+ .and_then(|mut file| file.read_to_string(&mut input).map_err(|e| Box::new(e) as Box<dyn Error>))
+ .and_then(|_| syn::parse_str(&input).map_err(|e| Box::new(e) as Box<dyn Error>))
+ .and_then(|nibble: File| nibble.convert().ok_or(Box::new(UndecVar) as Box<dyn Error>))
+ .and_then(|(funs, goal)| {
+ funs.into_iter()
+ .try_rfold(goal, |goal, function| {
+ goal.fold(&mut InlineCall::new(function))
+ })
+ .map_err(|e| Box::new(e) as Box<dyn Error>)
+ })
+ .and_then(|term| {
+ let mut context = Context::default();
+ term.fold(&mut TypeCheck {
+ context: &mut context,
+ })
+ .map_err(|e| Box::new(e) as Box<dyn Error>)
+ })
+ .map(|typed| {
+ let mut backend = RustBackend::default();
+ let id = typed.gen(&mut backend);
+ backend.emit_code(id)
+ })
+ .and_then(|code| {
+ fs::File::create(Path::new(&out_dir).join("nibble.rs"))
+ .and_then(|mut f| write!(f, "{}", code))
+ .map_err(|e| Box::new(e) as Box<dyn Error>)
+ });
+
+ if let Err(e) = res {
+ eprintln!("{}", e);
+ exit(1)
+ }
+}
diff --git a/autochomp/src/main.rs b/autochomp/src/main.rs
new file mode 100644
index 0000000..400cc2d
--- /dev/null
+++ b/autochomp/src/main.rs
@@ -0,0 +1,23 @@
+use std::{error::Error, io::{self, Read, Write}, process::exit};
+
+use chewed::Parse;
+
+mod nibble {
+ include!(concat!(env!("OUT_DIR"), "/nibble.rs"));
+}
+
+fn main() {
+ let mut input = String::new();
+ let res = io::stdin()
+ .read_to_string(&mut input)
+ .map_err(|e| Box::new(e) as Box<dyn Error>)
+ .and_then(|_| nibble::Ast::parse(input.chars().peekable()).map_err(|e| Box::new(e) as Box<dyn Error>))
+ .and_then(|ast| {
+ write!(io::stdout(), "{:?}", ast).map_err(|e| Box::new(e) as Box<dyn Error>)
+ });
+
+ if let Err(e) = res {
+ eprintln!("{}", e);
+ exit(1)
+ }
+}
diff --git a/autochomp/src/nibble.nb b/autochomp/src/nibble.nb
new file mode 100644
index 0000000..fed3d46
--- /dev/null
+++ b/autochomp/src/nibble.nb
@@ -0,0 +1,67 @@
+let opt(x) = _ | x;
+let plus(x) = [plus](x . opt(plus));
+let star(x) = opt(plus(x));
+let star_(base, step) = [rec](base | step . rec);
+
+let Pattern_Whitespace = "\t"|"\n"|"\x0B"|"\x0c"|"\r"|" "|"\u{85}"|"\u{200e}"|"\u{200f}"|"\u{2028}"|"\u{2029}";
+
+let digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
+let oct_digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7";
+let hex_digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" |
+ "a" | "b" | "c" | "d" | "e" | "f" |
+ "A" | "B" | "C" | "D" | "E" | "F" ;
+
+let XID_Start =
+ "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
+ "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
+ "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
+ "y" | "z" |
+ "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" |
+ "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" |
+ "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" |
+ "Y" | "Z" ;
+let XID_Continue =
+ XID_Start | "_" | "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
+
+let literal_char =
+ " " | "!" | "#" | "$" | "%" | "&" | "'" |
+ "(" | ")" | "*" | "+" | "," | "-" | "." | "/" |
+ "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
+ "8" | "9" | ":" | ";" | "<" | "=" | ">" | "?" |
+ "@" | "A" | "B" | "C" | "D" | "E" | "F" | "G" |
+ "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" |
+ "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" |
+ "X" | "Y" | "Z" | "[" | "]" | "^" | "_" |
+ "`" | "a" | "b" | "c" | "d" | "e" | "f" | "g" |
+ "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" |
+ "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" |
+ "x" | "y" | "z" | "{" | "|" | "}" | "~" |
+ "\\" . ("\"" | "'" | "n" | "r" | "t" | "\\" | "0" |
+ "x" . oct_digit . hex_digit |
+ "u{" . hex_digit . opt(hex_digit . opt(hex_digit . opt(hex_digit . opt(hex_digit . opt(hex_digit))))) . "}");
+
+let ws = plus(Pattern_Whitespace);
+
+let punctuated(x, p) = [rec](x . opt(p . opt(ws) . opt(rec)));
+let list(x) = "(" . opt(ws) . punctuated(x, ",") . ")";
+
+let epsilon = "_";
+let ident = XID_Start . star(XID_Continue);
+let literal = "\"" . plus(literal_char) . "\"";
+let parens(expr) = "(" . opt(ws) . expr . ")";
+let fix(expr) = "[" . opt(ws) . ident . opt(ws) . "]" . opt(ws) . parens(expr);
+
+let term(expr) =
+ epsilon . opt(ws)
+ | literal . opt(ws)
+ | parens(expr) . opt(ws)
+ | fix(expr) . opt(ws)
+ | ident . opt(ws) . opt(list(expr) . opt(ws))
+ ;
+
+let seq(expr) = punctuated(term(expr), ".");
+let alt(expr) = punctuated(seq(expr), "|");
+let expr = [expr](alt(expr));
+let let = "let" . ws . ident . opt(ws) . opt(list(ident . opt(ws)) . opt(ws)) . "=" . opt(ws) . expr . ";";
+let goal = "match" . ws . expr . ";";
+match star_(goal, let);
diff --git a/chewed/src/error.rs b/chewed/src/error.rs
index cb2cc4b..420a376 100644
--- a/chewed/src/error.rs
+++ b/chewed/src/error.rs
@@ -11,7 +11,7 @@ impl fmt::Display for TakeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BadBranch(got, expected) => {
- write!(f, "Unexpected character {:?}.", got)?;
+ write!(f, "Unexpected character {:?}. ", got)?;
if expected.is_empty() {
write!(f, "Expected end of input.")
@@ -51,6 +51,8 @@ impl fmt::Display for ParseError {
}
}
+impl Error for ParseError {}
+
impl From<TakeError> for ParseError {
fn from(e: TakeError) -> Self {
Self::TakeError(e)
diff --git a/chewed/src/parse.rs b/chewed/src/parse.rs
index 0687ea5..f6bbd66 100644
--- a/chewed/src/parse.rs
+++ b/chewed/src/parse.rs
@@ -1,3 +1,5 @@
+use std::iter::Peekable;
+
use super::error::{ParseError, TakeError};
pub trait Parser: Iterator<Item = char> {
@@ -37,6 +39,12 @@ pub trait Parser: Iterator<Item = char> {
}
}
+impl<I: Iterator<Item = char>> Parser for Peekable<I> {
+ fn peek(&mut self) -> Option<char> {
+ Peekable::peek(self).copied()
+ }
+}
+
pub trait Parse: Sized {
fn take<P: Parser + ?Sized>(input: &mut P) -> Result<Self, TakeError>;
diff --git a/examples/autochomp/main.rs b/examples/autochomp/main.rs
deleted file mode 100644
index afa489f..0000000
--- a/examples/autochomp/main.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub fn main() {
- todo!("Create AutoChomp")
-}
diff --git a/src/chomp/error.rs b/src/chomp/error.rs
index 6733d06..d0a3cc8 100644
--- a/src/chomp/error.rs
+++ b/src/chomp/error.rs
@@ -291,7 +291,7 @@ impl Display for FixError {
let start = self.0.span().unwrap_or_else(Span::call_site).start();
write!(
f,
- "\n({}:{}) assuming `{}' has type {:?}.",
+ "\n{}:{}: assuming `{}' has type {:?}.",
start.line,
start.column,
self.0.arg(),
diff --git a/src/lower/rust.rs b/src/lower/rust.rs
index c236bdd..fab040b 100644
--- a/src/lower/rust.rs
+++ b/src/lower/rust.rs
@@ -66,6 +66,7 @@ impl Backend for RustBackend {
);
let tokens = quote! {
#[doc=#doc_name]
+ #[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct #name;
impl Parse for #name {
@@ -128,6 +129,7 @@ impl Backend for RustBackend {
let right_ty = self.data[right].0.clone();
let name = format_ident!("Alt{}", id);
let mut tokens = quote! {
+ #[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum #name {
Left(#left_ty),
Right(#right_ty),
@@ -170,7 +172,7 @@ impl Backend for RustBackend {
match input.peek().ok_or(TakeError::EndOfStream)? {
#(#iter_left)|* => input.take().map(Self::Left),
#(#iter_right)|* => input.take().map(Self::Right),
- c => input.error(TakeError::BadBranch(c, &[#(#iter_first),*]))
+ c => Err(TakeError::BadBranch(c, &[#(#iter_first),*]))
}
}
}
@@ -204,11 +206,12 @@ impl Backend for RustBackend {
let inner = inner.gen(self);
let inner_ty = self.data[inner].0.clone();
let tokens = quote! {
+ #[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct #name(#inner_ty);
impl Parse for #name {
fn take<P: Parser + ?Sized>(input: &mut P) -> Result<Self, TakeError> {
- input.parse().map(Self)
+ input.take().map(Self)
}
}
};