Skip to content

Commit

Permalink
demo: making Span not Copy
Browse files Browse the repository at this point in the history
  • Loading branch information
digama0 committed Oct 25, 2023
1 parent 25c8ad6 commit d92e56d
Show file tree
Hide file tree
Showing 25 changed files with 523 additions and 520 deletions.
4 changes: 2 additions & 2 deletions mm0-rs/components/mm0_util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ impl<T> SliceUninit<T> {
}

/// Points to a specific region of a source file by identifying the region's start and end points.
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct Span {
/// The byte index of the beginning of the span (inclusive).
pub start: usize,
Expand Down Expand Up @@ -603,7 +603,7 @@ impl fmt::Debug for FileSpan {
}
}
impl<'a> From<&'a FileSpan> for Span {
fn from(fsp: &'a FileSpan) -> Self { fsp.span }
fn from(fsp: &'a FileSpan) -> Self { fsp.span.clone() }
}

/// Try to get memory usage (resident set size) in bytes using the
Expand Down
2 changes: 1 addition & 1 deletion mm0-rs/components/mm0_util/src/lined_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl LinedString {
#[cfg(feature = "server")]
#[must_use]
pub fn to_loc(&self, fs: &crate::FileSpan) -> lsp_types::Location {
lsp_types::Location { uri: fs.file.url().clone(), range: self.to_range(fs.span) }
lsp_types::Location { uri: fs.file.url().clone(), range: self.to_range(fs.span.clone()) }
}

/// Get the total number of lines in the file (as a `u32` for LSP compatibility).
Expand Down
12 changes: 6 additions & 6 deletions mm0-rs/components/mm1_parser/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub enum Delimiter {
/// A dollar-delimited formula: $ .. $.
/// `f.0` is the span of the entire formula including the delimiters, and
/// `f.inner()` is the span of the interior (excluding `$` but including any inner whitespace).
#[derive(Copy, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct Formula(pub Span);
#[cfg(feature = "memory")]
mm0_deepsize::deep_size_0!(Formula);
Expand All @@ -46,7 +46,7 @@ impl Formula {
/// Information about constants can be found in the [notation grammar].
///
/// [notation grammar]: https://github.com/digama0/mm0/blob/master/mm0-hs/mm1.md#notations
#[derive(Copy, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct Const {
/// The underlying formula (dollar delimited token)
pub fmla: Formula,
Expand Down Expand Up @@ -162,7 +162,7 @@ impl Type {
pub fn span(&self) -> Span {
match self {
Type::DepType(d) => d.span(),
Type::Formula(f) => f.0,
Type::Formula(f) => f.0.clone(),
}
}
}
Expand Down Expand Up @@ -414,7 +414,7 @@ pub enum SimpleNotaKind {
/// Represents a notation item declared with the prefix, infixl, or infixr keywords. Notation
/// declared with the 'notation' keyword is represented by [`GenNota`]
#[cfg_attr(feature = "memory", derive(DeepSizeOf))]
#[derive(Copy, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct SimpleNota {
/// The initial notation keyword, one of `prefix`, `infixl`, or `infixr`.
pub k: SimpleNotaKind,
Expand All @@ -431,7 +431,7 @@ pub struct SimpleNota {
/// For example in `notation ab {x} (ph) = (${$:max) x ($|$:50) ph ($}$:0);` there
/// are 5 notation literals, `(${$:0)`, `x`, `($|$:50)`, `ph`, `($}$:0)`.
#[cfg_attr(feature = "memory", derive(DeepSizeOf))]
#[derive(Copy, Clone, Debug)]
#[derive(Clone, Debug)]
pub enum Literal {
/// A constant with a precedence, such as `($|$:50)`.
Const(Const, Prec),
Expand Down Expand Up @@ -587,7 +587,7 @@ impl Ast {
pub fn get_decl(&self, ident: &[u8]) -> Option<&Decl> {
for stmt in self.stmts_iter() {
if let StmtKind::Decl(decl @ Decl { .. }) = &stmt.k {
if self.span(decl.id) == ident {
if self.span(decl.id.clone()) == ident {
return Some(decl)
}
}
Expand Down
42 changes: 21 additions & 21 deletions mm0-rs/components/mm1_parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ type Result<T> = std::result::Result<T, ParseError>;

impl Clone for ParseError {
fn clone(&self) -> Self {
let &ParseError { pos, level, ref msg } = self;
ParseError { pos, level, msg: format!("{msg}").into() }
let &ParseError { ref pos, level, ref msg } = self;
ParseError { pos: pos.clone(), level, msg: format!("{msg}").into() }
}
}

Expand All @@ -164,7 +164,7 @@ impl ParseError {
#[must_use]
pub fn to_diag(&self, file: &LinedString) -> Diagnostic {
Diagnostic {
range: file.to_range(self.pos),
range: file.to_range(self.pos.clone()),
severity: Some(self.level.to_diag_severity()),
code: None,
code_description: None,
Expand Down Expand Up @@ -395,8 +395,8 @@ impl<'a> Parser<'a> {
loop {
self.idx += 1;
if !self.cur_opt().map_or(false, ident_rest) {
let sp = (start..self.idx).into();
if self.restart_pos.is_none() && CommandKeyword::parse(self.span(sp)).is_some() {
let sp: Span = (start..self.idx).into();
if self.restart_pos.is_none() && CommandKeyword::parse(self.span(sp.clone())).is_some() {
self.restart_pos = Some(start);
}
self.ws();
Expand All @@ -408,7 +408,7 @@ impl<'a> Parser<'a> {
/// Attempt to parse an `ident`. This is the same as [`ident_`](Self::ident_),
/// except that `_` is not accepted.
/// On success, advances past the ident and any trailing whitespace.
fn ident(&mut self) -> Option<Span> { self.ident_().filter(|&s| self.span(s) != b"_") }
fn ident(&mut self) -> Option<Span> { self.ident_().filter(|s| self.span(s.clone()) != b"_") }

/// Attempt to parse an ident or blank, returning an error on failure.
fn ident_err_(&mut self) -> Result<Span> {
Expand Down Expand Up @@ -449,7 +449,7 @@ impl<'a> Parser<'a> {
loop {
match self.ident_() {
None => return (modifiers, None),
Some(id) => match Modifiers::from_name(self.span(id)) {
Some(id) => match Modifiers::from_name(self.span(id.clone())) {
Modifiers::NONE => return (modifiers, Some(id)),
m => {
if modifiers.intersects(m) {
Expand Down Expand Up @@ -489,7 +489,7 @@ impl<'a> Parser<'a> {
let dummy = self.chr(b'.').is_some();
let x = if dummy { Some(self.ident_err_()?) } else { self.ident_() };
if let Some(x) = x {
let k = if self.span(x) == b"_" {
let k = if self.span(x.clone()) == b"_" {
LocalKind::Anon
} else if dummy {
LocalKind::Dummy
Expand All @@ -516,7 +516,7 @@ impl<'a> Parser<'a> {
let mut bis = Vec::new();
while let Some((span, locals, ty)) = self.binder_group()? {
bis.extend(locals.into_iter().map(|(x, kind)| Binder {
span,
span: span.clone(),
local: Some(x),
kind,
ty: ty.clone(),
Expand Down Expand Up @@ -665,7 +665,7 @@ impl<'a> Parser<'a> {

fn is_atom(&self, e: &SExpr, s: &[u8]) -> bool {
if let SExpr { span, k: SExprKind::Atom(Atom::Ident) } = e {
self.span(*span) == s
self.span(span.clone()) == s
} else {
false
}
Expand All @@ -691,7 +691,7 @@ impl<'a> Parser<'a> {
) -> SExpr {
SExpr::curly_list(span.into(), curly, es, dot, |e1, e2| match (&e1.k, &e2.k) {
(SExprKind::Atom(Atom::Ident), SExprKind::Atom(Atom::Ident)) =>
self.span(e1.span) == self.span(e2.span),
self.span(e1.span.clone()) == self.span(e2.span.clone()),
_ => false,
})
}
Expand Down Expand Up @@ -760,7 +760,7 @@ impl<'a> Parser<'a> {
Some(b'#') => {
self.idx += 1;
let mut span = self.ident_err()?;
match (self.span(span), span.start -= 1).0 {
match (self.span(span.clone()), span.start -= 1).0 {
b"t" => Ok(SExpr { span, k: SExprKind::Bool(true) }),
b"f" => Ok(SExpr { span, k: SExprKind::Bool(false) }),
b"undef" => Ok(SExpr { span, k: SExprKind::Undef }),
Expand All @@ -774,7 +774,7 @@ impl<'a> Parser<'a> {
Some(b'$') => {
// Safety: `formula()` only returns `Ok(None)` on non-`$` input
let f = unsafe { self.formula()?.unwrap_unchecked() };
Ok(SExpr { span: f.0, k: SExprKind::Formula(f) })
Ok(SExpr { span: f.0.clone(), k: SExprKind::Formula(f) })
}
Some(c) if c.is_ascii_digit() => {
let (span, n) = self.number()?;
Expand Down Expand Up @@ -819,21 +819,21 @@ impl<'a> Parser<'a> {
fn cnst(&mut self) -> Result<Const> {
let fmla = self.formula()?.ok_or_else(|| self.err("expected a constant".into()))?;
let mut trim = fmla.inner();
for i in trim.into_iter().rev() {
for i in trim.clone().into_iter().rev() {
if whitespace(self.source[i]) {
trim.end -= 1
} else {
break
}
}
for i in trim {
for i in trim.clone() {
if whitespace(self.source[i]) {
trim.start += 1
} else {
break
}
}
if { trim }.any(|i| whitespace(self.source[i])) {
if { trim.clone() }.any(|i| whitespace(self.source[i])) {
return Err(ParseError::new(trim, "constant contains embedded whitespace".into()))
}
if trim.start >= trim.end {
Expand All @@ -853,7 +853,7 @@ impl<'a> Parser<'a> {
_ => {
self
.ident_()
.filter(|&id| self.span(id) == b"max")
.filter(|id| self.span(id.clone()) == b"max")
.ok_or_else(|| self.err("expected number or 'max'".into()))?;
Ok(Prec::Max)
}
Expand All @@ -866,7 +866,7 @@ impl<'a> Parser<'a> {
let c = self.cnst()?;
self
.ident_()
.filter(|&id| self.span(id) == b"prec")
.filter(|id| self.span(id.clone()) == b"prec")
.ok_or_else(|| self.err("expected 'prec'".into()))?;
let prec = self.prec()?;
Ok((self.chr_err(b';')?, SimpleNota { k, id, c, prec }))
Expand Down Expand Up @@ -983,7 +983,7 @@ impl<'a> Parser<'a> {
self.err_str("expected command keyword")
},
(mut m, Some(id)) => {
let k = self.span(id);
let k = self.span(id.clone());
match CommandKeyword::parse(k) {
Some(CommandKeyword::Sort) => {
if !Modifiers::sort_data().contains(m) {
Expand Down Expand Up @@ -1073,11 +1073,11 @@ impl<'a> Parser<'a> {
self.modifiers_empty(m, id, "import statements do not take modifiers");
let (sp, s) = self.string()?;
let span = (start..self.chr_err(b';')?).into();
self.imports.push((sp, s.clone()));
self.imports.push((sp.clone(), s.clone()));
Ok(Some(Stmt::new(span, StmtKind::Import(sp, s))))
}
Some(CommandKeyword::Exit) => {
self.modifiers_empty(m, id, "exit does not take modifiers");
self.modifiers_empty(m, id.clone(), "exit does not take modifiers");
self.chr_err(b';')?;
self.errors.push(ParseError::new(id, "early exit on 'exit' command".into()));
Ok(None)
Expand Down
8 changes: 4 additions & 4 deletions mm0-rs/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ fn mk_to_range() -> impl FnMut(&FileSpan) -> Option<Range> {
move |fsp: &FileSpan| -> Option<Range> {
srcs.entry(fsp.file.ptr())
.or_insert_with(|| VFS.0.ulock()[&fsp.file].text.clone())
.try_ascii().map(|f| f.to_range(fsp.span))
.try_ascii().map(|f| f.to_range(fsp.span.clone()))
}
}

Expand Down Expand Up @@ -297,7 +297,7 @@ impl ElabError {
fn to_snippet<T>(&self, path: &FileRef, file: &LinedString,
to_range: impl FnMut(&FileSpan) -> Option<Range>,
f: impl for<'a> FnOnce(Snippet<'a>) -> T) -> T {
f(make_snippet(path, file, self.pos, &self.kind.msg(), self.level,
f(make_snippet(path, file, self.pos.clone(), &self.kind.msg(), self.level,
self.kind.to_footer(&Arena::new(), to_range)))
}

Expand All @@ -323,7 +323,7 @@ impl ElabError {
/// about the parameters.
fn to_snippet<T>(err: &ParseError, path: &FileRef, file: &LinedString,
f: impl for<'a> FnOnce(Snippet<'a>) -> T) -> T {
f(make_snippet(path, file, err.pos, &format!("{}", err.msg), err.level, vec![]))
f(make_snippet(path, file, err.pos.clone(), &format!("{}", err.msg), err.level, vec![]))
}

fn log_msg(#[allow(unused_mut)] mut s: String) {
Expand Down Expand Up @@ -429,7 +429,7 @@ async fn elaborate(path: FileRef, rd: ArcList<FileRef>) -> io::Result<ElabResult
} else {
for e in &errors {
level = level.max(e.level as u8);
e.to_snippet_no_source(&path, e.pos, print)
e.to_snippet_no_source(&path, e.pos.clone(), print)
}
}
MAX_EMITTED_ERROR.fetch_max(level, Ordering::Relaxed);
Expand Down
2 changes: 1 addition & 1 deletion mm0-rs/src/doc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ impl<'a, W: Write> BuildDoc<'a, W> {
use std::fmt::Write;
let url = base.join(filename).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
write!(nav, " | <a href=\"{url}").expect("writing to a string");
let range = self.source.to_range(td.full);
let range = self.source.to_range(td.full.clone());
if range.start.line == range.end.line {
write!(nav, "#L{}\">src</a>", range.start.line + 1)
} else {
Expand Down
Loading

0 comments on commit d92e56d

Please sign in to comment.