MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / getPrecedingDocstring

Function getPrecedingDocstring

src/extraction/tree-sitter-helpers.ts:170–241  ·  view source on GitHub ↗
(
  node: SyntaxNode,
  source: string,
  stepOver: readonly string[] = [],
  skipTrailing = false,
  skipDetached = false,
  skipDirectives = false
)

Source from the content-addressed store, hash-verified

168 * where the docstring starts. Default: off.
169 */
170export function getPrecedingDocstring(
171 node: SyntaxNode,
172 source: string,
173 stepOver: readonly string[] = [],
174 skipTrailing = false,
175 skipDetached = false,
176 skipDirectives = false
177): string | undefined {
178 // Climb out of any wrapper(s) so a comment preceding the WHOLE construct
179 // (export-, decorator-, or const-arrow-wrapped) is reachable as a sibling.
180 // The emitted node's own `previousNamedSibling` is empty (export/const) or a
181 // decorator (Python) in those cases, so without this the docstring was
182 // dropped. (#780)
183 let anchor = node;
184 while (anchor.parent && DOCSTRING_WRAPPER_TYPES.has(anchor.parent.type)) {
185 anchor = anchor.parent;
186 }
187
188 let sibling = anchor.previousNamedSibling;
189 const comments: SyntaxNode[] = [];
190
191 while (sibling) {
192 if (
193 sibling.type === 'comment' ||
194 sibling.type === 'line_comment' ||
195 sibling.type === 'block_comment' ||
196 sibling.type === 'documentation_comment'
197 ) {
198 comments.unshift(sibling);
199 sibling = sibling.previousNamedSibling;
200 } else if (stepOver.includes(sibling.type)) {
201 sibling = sibling.previousNamedSibling;
202 } else {
203 break;
204 }
205 }
206
207 let first = 0;
208 if (skipTrailing) {
209 let endRow = -1;
210 for (const comment of comments) {
211 const trails =
212 first === 0 ? followsCodeOnItsLine(comment, source) : comment.startPosition.row === endRow;
213 if (!trails) break;
214 endRow = comment.endPosition.row;
215 first++;
216 }
217 }
218 if (skipDetached) {
219 // Walk back from the declaration: the last comment must end on the line
220 // above it, and each one before joins while it ends on the line the next
221 // one starts, or the line before that.
222 let start = comments.length;
223 if (start > first && comments[start - 1]!.endPosition.row + 1 === anchor.startPosition.row) {
224 start--;
225 while (start > first && comments[start - 1]!.endPosition.row + 1 >= comments[start]!.startPosition.row) {
226 start--;
227 }

Callers 3

docstringForMethod · 0.90
handleFunDeclFunction · 0.90
handleRecordDeclFunction · 0.90

Calls 7

followsCodeOnItsLineFunction · 0.85
isDirectiveFunction · 0.85
getNodeTextFunction · 0.85
cleanCommentMarkersFunction · 0.85
hasMethod · 0.80
mapMethod · 0.80
joinMethod · 0.45

Tested by

no test coverage detected