2021-09-21 10:43:23 -04:00
|
|
|
// XIRT attributes
|
|
|
|
//
|
|
|
|
// Copyright (C) 2014-2021 Ryan Specialty Group, LLC.
|
|
|
|
//
|
|
|
|
// This file is part of TAME.
|
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
//! XIRT attributes.
|
|
|
|
//!
|
2021-09-21 15:30:44 -04:00
|
|
|
//! Attributes are represented by [`Attr`].
|
|
|
|
//!
|
|
|
|
//! See [parent module](super) for additional documentation.
|
2021-09-21 10:43:23 -04:00
|
|
|
|
tamer: xir::tree::attr_parser_from: Integrate AttrParser
This begins to integrate the isolated AttrParser. The next step will be
integrating it into the larger XIRT parser.
There's been considerable delay in getting this committed, because I went
through quite the struggle with myself trying to determine what balance I
want to strike between Rust's type system; convenience with parser
combinators; iterators; and various other abstractions. I ended up being
confounded by trying to maintain the current XmloReader abstraction, which
is fundamentally incompatible with the way the new parsing system
works (streaming iterators that do not collect or perform heap
allocations).
There'll be more information on this to come, but there are certain things
that will be changing.
There are a couple problems highlighted by this commit (not in code, but
conceptually):
1. Introducing Option here for the TokenParserState doesn't feel right, in
the sense that the abstraction is inappropriate. We should perhaps
introduce a new variant Parsed::Done or something to indicate intent,
rather than leaving the reader to have to read about what None actually
means.
2. This turns Parsed into more of a statement influencing control
flow/logic, and so should be encapsulated, with an external equivalent
of Parsed that omits variants that ought to remain encapsulated.
3. TokenStreamState is true, but these really are the actual parsers;
TokenStreamParser is more of a coordinator, and helps to abstract away
some of the common logic so lower-level parsers do not have to worry
about it. But calling it TokenStreamState is both a bit
confusing and is an understatement---it _does_ hold the state, but it
also holds the current parsing stack in its variants.
Another thing that is not yet entirely clear is whether this AttrParser
ought to care about detection of duplicate attributes, or if that should be
done in a separate parser, perhaps even at the XIR level. The same can be
said for checking for balanced tags. By pushing it to TokenStream in XIR,
we would get a guaranteed check regardless of what parsers are used, which
is attractive because it reduces the (almost certain-to-otherwise-occur)
risk that individual parsers will not sufficiently check for semantically
valid XML. But it does _potentially_ match error recovery more
complicated. But at the same time, perhaps more specific parsers ought not
care about recovery at that level.
Anyway, point being, more to come, but I am disappointed how much time I'm
spending considering parsing, given that there are so many things I need to
move onto. I just want this done right and in a way that feels like it's
working well with Rust while it's all in working memory, otherwise it's
going to be a significant effort to get back into.
DEV-11268
2021-12-10 14:13:02 -05:00
|
|
|
mod parse;
|
|
|
|
|
tamer: xir::escape: Remove XirString in favor of Escaper
This rewrites a good portion of the previous commit.
Rather than explicitly storing whether a given string has been escaped, we
can instead assume that all SymbolIds leaving or entering XIR are unescaped,
because there is no reason for any other part of the system to deal with
such details of XML documents.
Given that, we need only unescape on read and escape on write. This is
customary, so why didn't I do that to begin with?
The previous commit outlines the reason, mainly being an optimization for
the echo writer that is upcoming. However, this solution will end up being
better---it's not implemented yet, but we can have a caching layer, such
that the Escaper records a mapping between escaped and unescaped SymbolIds
to avoid work the next time around. If we share the Escaper between _all_
readers and the writer, the result is that
1. Duplicate strings between source files and object files (many of which
are read by both the linker and compiler) avoid re-unescaping; and
2. Writers can use this cache to avoid re-escaping when we've already seen
the escaped variant of the string during read.
The alternative would be a global cache, like the internment system, but I
did not find that to be appropriate here, since this is far less
fundamental and is much easier to compose.
DEV-11081
2021-11-12 13:59:14 -05:00
|
|
|
use super::QName;
|
2022-03-21 13:40:54 -04:00
|
|
|
use crate::{parse::Token, span::Span, sym::SymbolId};
|
2021-11-23 13:05:10 -05:00
|
|
|
use std::fmt::Display;
|
2021-09-21 10:43:23 -04:00
|
|
|
|
2021-12-17 10:22:05 -05:00
|
|
|
pub use parse::{AttrParseError, AttrParseState};
|
tamer: xir:tree: Begin work on composable XIRT parser
The XIRT parser was initially written for test cases, so that unit tests
should assert more easily on generated token streams (XIR). While it was
planned, it wasn't clear what the eventual needs would be, which were
expected to differ. Indeed, loading everything into a generic tree
representation in memory is not appropriate---we should prefer streaming and
avoiding heap allocations when they’re not necessary, and we should parse
into an IR rather than a generic format, which ensures that the data follow
a proper grammar and are semantically valid.
When parsing attributes in an isolated context became necessary for the
aforementioned task, the state machine of the XIRT parser was modified to
accommodate. The opposite approach should have been taken---instead of
adding complexity and special cases to the parser, and from a complex parser
extracting a simple one (an attribute parser), we should be composing the
larger (full XIRT) parser from smaller ones (e.g. attribute, child
elements).
A combinator, when used in a functional sense, refers not to combinatory
logic but to the composition of more complex systems from smaller ones. The
changes made as part of this commit begin to work toward combinators, though
it's not necessarily evident yet (to you, the reader) how that'll work,
since the code for it hasn't yet been written; this is commit is simply
getting my work thusfar introduced so I can do some light refactoring before
continuing on it.
TAMER does not aim to introduce a parser combinator framework in its usual
sense---it favors, instead, striking a proper balance with Rust’s type
system that permits the convenience of combinators only in situations where
they are needed, to avoid having to write new parser
boilerplate. Specifically:
1. Rust’s type system should be used as combinators, so that parsers are
automatically constructed from the type definition.
2. Primitive parsers are written as explicit automata, not as primitive
combinators.
3. Parsing should directly produce IRs as a lowering operation below XIRT,
rather than producing XIRT itself. That is, target IRs should consume
XIRT and produce parse themselves immediately, during streaming.
In the future, if more combinators are needed, they will be added; maybe
this will eventually evolve into a more generic parser combinator framework
for TAME, but that is certainly a waste of time right now. And, to be
honest, I’m hoping that won’t be necessary.
2021-12-06 11:26:53 -05:00
|
|
|
|
2021-12-06 14:26:58 -05:00
|
|
|
/// Element attribute.
|
2021-09-21 10:43:23 -04:00
|
|
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
2021-12-06 14:26:58 -05:00
|
|
|
pub struct Attr {
|
|
|
|
name: QName,
|
|
|
|
value: SymbolId,
|
|
|
|
/// Spans for the attribute name and value respectively.
|
|
|
|
span: (Span, Span),
|
2021-09-21 15:30:44 -04:00
|
|
|
}
|
|
|
|
|
2021-09-23 14:52:53 -04:00
|
|
|
impl Attr {
|
2021-09-21 15:30:44 -04:00
|
|
|
/// Construct a new simple attribute with a name, value, and respective
|
|
|
|
/// [`Span`]s.
|
|
|
|
#[inline]
|
tamer: xir::escape: Remove XirString in favor of Escaper
This rewrites a good portion of the previous commit.
Rather than explicitly storing whether a given string has been escaped, we
can instead assume that all SymbolIds leaving or entering XIR are unescaped,
because there is no reason for any other part of the system to deal with
such details of XML documents.
Given that, we need only unescape on read and escape on write. This is
customary, so why didn't I do that to begin with?
The previous commit outlines the reason, mainly being an optimization for
the echo writer that is upcoming. However, this solution will end up being
better---it's not implemented yet, but we can have a caching layer, such
that the Escaper records a mapping between escaped and unescaped SymbolIds
to avoid work the next time around. If we share the Escaper between _all_
readers and the writer, the result is that
1. Duplicate strings between source files and object files (many of which
are read by both the linker and compiler) avoid re-unescaping; and
2. Writers can use this cache to avoid re-escaping when we've already seen
the escaped variant of the string during read.
The alternative would be a global cache, like the internment system, but I
did not find that to be appropriate here, since this is far less
fundamental and is much easier to compose.
DEV-11081
2021-11-12 13:59:14 -05:00
|
|
|
pub fn new(name: QName, value: SymbolId, span: (Span, Span)) -> Self {
|
2021-12-06 14:26:58 -05:00
|
|
|
Self { name, value, span }
|
2021-09-21 15:30:44 -04:00
|
|
|
}
|
2021-09-28 14:52:31 -04:00
|
|
|
|
|
|
|
/// Attribute name.
|
|
|
|
#[inline]
|
|
|
|
pub fn name(&self) -> QName {
|
2021-12-06 14:26:58 -05:00
|
|
|
self.name
|
2021-09-28 14:52:31 -04:00
|
|
|
}
|
|
|
|
|
2021-12-06 14:26:58 -05:00
|
|
|
/// Retrieve the value from the attribute.
|
2021-09-28 14:52:31 -04:00
|
|
|
///
|
tamer: xir::escape: Remove XirString in favor of Escaper
This rewrites a good portion of the previous commit.
Rather than explicitly storing whether a given string has been escaped, we
can instead assume that all SymbolIds leaving or entering XIR are unescaped,
because there is no reason for any other part of the system to deal with
such details of XML documents.
Given that, we need only unescape on read and escape on write. This is
customary, so why didn't I do that to begin with?
The previous commit outlines the reason, mainly being an optimization for
the echo writer that is upcoming. However, this solution will end up being
better---it's not implemented yet, but we can have a caching layer, such
that the Escaper records a mapping between escaped and unescaped SymbolIds
to avoid work the next time around. If we share the Escaper between _all_
readers and the writer, the result is that
1. Duplicate strings between source files and object files (many of which
are read by both the linker and compiler) avoid re-unescaping; and
2. Writers can use this cache to avoid re-escaping when we've already seen
the escaped variant of the string during read.
The alternative would be a global cache, like the internment system, but I
did not find that to be appropriate here, since this is far less
fundamental and is much easier to compose.
DEV-11081
2021-11-12 13:59:14 -05:00
|
|
|
/// Since [`SymbolId`] implements [`Copy`],
|
2021-09-28 14:52:31 -04:00
|
|
|
/// this returns an owned value.
|
|
|
|
#[inline]
|
2021-12-06 14:26:58 -05:00
|
|
|
pub fn value(&self) -> SymbolId {
|
|
|
|
self.value
|
2021-09-28 14:52:31 -04:00
|
|
|
}
|
2021-09-21 15:30:44 -04:00
|
|
|
}
|
|
|
|
|
2022-03-21 13:40:54 -04:00
|
|
|
impl Token for Attr {
|
|
|
|
fn span(&self) -> Span {
|
|
|
|
// TODO: This may or may not actually represent the span relative to
|
|
|
|
// a given parser,
|
|
|
|
// so we may want to accept a context to bias toward.
|
|
|
|
self.span.1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-23 13:05:10 -05:00
|
|
|
impl Display for Attr {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "`@{}=\"{}\"` at {}", self.name, self.value, self.span.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-21 10:43:23 -04:00
|
|
|
/// List of attributes.
|
|
|
|
///
|
|
|
|
/// Attributes are ordered in XIR so that this IR will be suitable for code
|
|
|
|
/// formatters and linters.
|
|
|
|
///
|
|
|
|
/// This abstraction will allow us to manipulate the internal data so that
|
|
|
|
/// it is suitable for a particular task in the future
|
|
|
|
/// (e.g. O(1) lookups by attribute name).
|
|
|
|
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
2021-09-23 14:52:53 -04:00
|
|
|
pub struct AttrList {
|
|
|
|
attrs: Vec<Attr>,
|
2021-09-21 10:43:23 -04:00
|
|
|
}
|
|
|
|
|
2021-09-23 14:52:53 -04:00
|
|
|
impl AttrList {
|
2021-09-21 10:43:23 -04:00
|
|
|
/// Construct a new, empty attribute list.
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self { attrs: vec![] }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add an attribute to the end of the attribute list.
|
2021-11-02 14:07:20 -04:00
|
|
|
pub fn push(mut self, attr: Attr) -> Self {
|
|
|
|
self.attrs.push(attr);
|
|
|
|
self
|
2021-09-21 10:43:23 -04:00
|
|
|
}
|
2021-09-28 14:52:31 -04:00
|
|
|
|
|
|
|
/// Search for an attribute of the given `name`.
|
|
|
|
///
|
|
|
|
/// _You should use this method only when a linear search makes sense._
|
|
|
|
///
|
|
|
|
/// This performs an `O(n)` linear search in the worst case.
|
|
|
|
/// Future implementations may perform an `O(1)` lookup under certain
|
|
|
|
/// circumstances,
|
|
|
|
/// but this should not be expected.
|
|
|
|
pub fn find(&self, name: QName) -> Option<&Attr> {
|
|
|
|
self.attrs.iter().find(|attr| attr.name() == name)
|
|
|
|
}
|
2021-11-03 14:37:05 -04:00
|
|
|
|
|
|
|
/// Returns [`true`] if the list contains no attributes.
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
self.attrs.is_empty()
|
|
|
|
}
|
2021-09-21 10:43:23 -04:00
|
|
|
}
|
|
|
|
|
2021-09-23 14:52:53 -04:00
|
|
|
impl From<Vec<Attr>> for AttrList {
|
|
|
|
fn from(attrs: Vec<Attr>) -> Self {
|
2021-09-21 10:43:23 -04:00
|
|
|
AttrList { attrs }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
tamer: xir::tree::attr_parser_from: Integrate AttrParser
This begins to integrate the isolated AttrParser. The next step will be
integrating it into the larger XIRT parser.
There's been considerable delay in getting this committed, because I went
through quite the struggle with myself trying to determine what balance I
want to strike between Rust's type system; convenience with parser
combinators; iterators; and various other abstractions. I ended up being
confounded by trying to maintain the current XmloReader abstraction, which
is fundamentally incompatible with the way the new parsing system
works (streaming iterators that do not collect or perform heap
allocations).
There'll be more information on this to come, but there are certain things
that will be changing.
There are a couple problems highlighted by this commit (not in code, but
conceptually):
1. Introducing Option here for the TokenParserState doesn't feel right, in
the sense that the abstraction is inappropriate. We should perhaps
introduce a new variant Parsed::Done or something to indicate intent,
rather than leaving the reader to have to read about what None actually
means.
2. This turns Parsed into more of a statement influencing control
flow/logic, and so should be encapsulated, with an external equivalent
of Parsed that omits variants that ought to remain encapsulated.
3. TokenStreamState is true, but these really are the actual parsers;
TokenStreamParser is more of a coordinator, and helps to abstract away
some of the common logic so lower-level parsers do not have to worry
about it. But calling it TokenStreamState is both a bit
confusing and is an understatement---it _does_ hold the state, but it
also holds the current parsing stack in its variants.
Another thing that is not yet entirely clear is whether this AttrParser
ought to care about detection of duplicate attributes, or if that should be
done in a separate parser, perhaps even at the XIR level. The same can be
said for checking for balanced tags. By pushing it to TokenStream in XIR,
we would get a guaranteed check regardless of what parsers are used, which
is attractive because it reduces the (almost certain-to-otherwise-occur)
risk that individual parsers will not sufficiently check for semantically
valid XML. But it does _potentially_ match error recovery more
complicated. But at the same time, perhaps more specific parsers ought not
care about recovery at that level.
Anyway, point being, more to come, but I am disappointed how much time I'm
spending considering parsing, given that there are so many things I need to
move onto. I just want this done right and in a way that feels like it's
working well with Rust while it's all in working memory, otherwise it's
going to be a significant effort to get back into.
DEV-11268
2021-12-10 14:13:02 -05:00
|
|
|
impl FromIterator<Attr> for AttrList {
|
|
|
|
fn from_iter<T: IntoIterator<Item = Attr>>(iter: T) -> Self {
|
|
|
|
iter.into_iter().collect::<Vec<Attr>>().into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-23 14:52:53 -04:00
|
|
|
impl<const N: usize> From<[Attr; N]> for AttrList {
|
|
|
|
fn from(attrs: [Attr; N]) -> Self {
|
2021-09-21 10:43:23 -04:00
|
|
|
AttrList {
|
|
|
|
attrs: attrs.into(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-06 14:26:58 -05:00
|
|
|
// See [`super::test`] for tests related to attributes.
|