-
Hi 👋🏻, Considering the following Lua code, I just wanted to only pick the lines that start with a comment (ie. local U = {} ---Ignore until eol
---@class CMode Comment modes - Can be manual or computed in operator-pending phase
---@field toggle number Toggle action
---@field comment number Comment action
---@field uncomment number Uncomment action
---@see VMode
---@see Mee
print("ignore this")
print("and this")
---Takes out the leading indent from lines
---@param str string
---@return string string Indent chars
---@return number string Length of the indent chars
---@see VMode
---@see Mee
function U.grab_indent(str)
local _, len, indent = str:find("^(%s*)")
return indent, len
end
return U
So I came up with the following where I ignore the useless nodes using use chumsky::{
prelude::{choice, filter, just, take_until, Simple},
text::{self, newline, TextParser},
Parser,
};
#[derive(Debug)]
pub struct Lua;
impl Lua {
pub fn parse(src: &str) -> Result<Vec<Option<String>>, Vec<Simple<char>>> {
let node = choice((
just("---")
.then(filter(|c| *c != '\n').repeated().collect::<String>())
.map(|(s, x)| format!("{s}{x}")),
text::keyword("function")
.ignore_then(filter(|x| *x != '(').repeated().collect().padded()),
))
.map(Some);
let misc = text::ident().then_ignore(take_until(newline())).to(None);
choice((node.padded(), misc))
.repeated()
.collect()
.parse(src)
}
} NOTE: With functions, I am only interested in the name. So I am wondering Is there a nicer way to do this? Like, remove the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It seems I was on the right path and just missing the use chumsky::{
prelude::{any, choice, filter, just, take_until, Simple},
text::{self, newline, TextParser},
Parser,
};
#[derive(Debug)]
pub struct Lua;
impl Lua {
pub fn parse(src: &str) -> Result<Vec<String>, Vec<Simple<char>>> {
let node = choice((
just("---")
.then(filter(|c| *c != '\n').repeated().collect::<String>())
.map(|(s, x)| format!("{s}{x}")),
text::keyword("function")
.ignore_then(filter(|x| *x != '(').repeated().collect().padded()),
))
.map(Some);
let misc = any().then(take_until(newline())).to(None);
choice((node.padded(), misc))
.repeated()
.flatten() // I was missing this
.parse(src)
}
} |
Beta Was this translation helpful? Give feedback.
It seems I was on the right path and just missing the
.flatten()
combinator at the end. I am not sure whether this is correct or not, but I got the result that I wanted. Here is the new code