how to extract preceding comment from a statement?
wez opened this issue · 6 comments
I don't see an obvious way from the API docs to to access the comments from the ast for something like this:
---@class Foo
---@field name string the name of the Foo
local Foo = {}
what's the recommended way to be able to extract the uninterrupted sequence of comments that precedes an ast node?
Does leading_trivia()
do what you want?
I don't know what it does?
and by that I mean, the docs don't specify what leading trivia is, or its scope:
https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.TokenReference.html#method.leading_trivia
can you clarify the behavior? What is exactly is trivia in this context?
Oh, surrounding_trivia() will work too. https://docs.rs/full_moon/latest/full_moon/node/trait.Node.html#method.surrounding_trivia
Trivia is whitespace and comments, anything that doesn't have a node on its own.
I see, so parse()
will yield an Ast
, and from there ast.nodes()
will yield each node, and node.surrounding_trivia()
will get the before/after tokens.
Yup, that's correct. The preceding comment of each statement is attached as leading trivia of the first token in the statement. Generally, it can be accessed using node.surrounding_trivia()
on the Node
trait that each specialised node implements.
You can also treat each statement node individually if you wish. For the example in OP, you have a LocalAssignment
, and the two comments are leading trivia on the LocalAssignment::local_token()