Skip to content

Commit

Permalink
init: doc comment support
Browse files Browse the repository at this point in the history
Co-authored-by: Shahar Dawn Or <mightyiampresence@gmail.com>
  • Loading branch information
hsjobeki and mightyiam committed Feb 11, 2024
1 parent dcd764e commit 490ed95
Show file tree
Hide file tree
Showing 18 changed files with 841 additions and 285 deletions.
64 changes: 63 additions & 1 deletion CHANGELOG.md
@@ -1,8 +1,70 @@
# Changelog

## Version 3.0.0

### New Features

- **Official Doc-Comments Support:** We've introduced support for official doc-comments as defined in [RFC145](https://github.com/NixOS/rfcs/pull/145). This enhancement aligns nixdoc with our latest documentation standard.

### Deprecated Features

- **Legacy Custom Format:** The custom nixdoc format is now considered a legacy feature. We plan to phase it out in future versions to streamline documentation practices.
- We encourage users to transition to the official doc-comment format introduced in this release.
- We will continue to maintain the legacy format, we will not accept new features or enhancements for it. This decision allows for a period of transition to the new documentation practices.

### Migration Guide: Upgrading from nixdoc < 2.x.x to 3.x.x

To leverage the new doc-comment features and prepare for the deprecation of the legacy format, follow these guidelines:

#### Documentation Comments

- Use double asterisks `/** */` to mark comments intended as documentation. This differentiates them from internal comments and ensures they are properly processed as part of the documentation.

#### Documenting Arguments

- With the introduction of RFC145, there is a shift in how arguments are documented. While direct "argument" documentation is not specified, you can still document arguments effectively within your nix expressions.

**Example:** Migrating Single Argument Documentation
The approach to documenting single arguments has evolved. Instead of individual argument comments, document the function and its arguments together.

```nix
{
/**
* The `id` function returns the provided value unchanged.
*
* # Arguments
* - `x` (`Any`): The value to be returned.
*/
id = x: x;
}
```

**Example:** Documenting Structured Arguments
Structured arguments can be documented similarly to lambda formals, using doc-comments for clarity and organization.

```nix
{
/**
* The `add` function calculates the sum of `a` and `b`.
*/
add = {
/** The first number to add. */
a,
/** The second number to add. */
b
}: a + b;
}
```

Ensure your documentation comments start with double asterisks to comply with the new standard. The legacy format remains supported for now but will not receive new features. It will be removed once all important downstream projects have been migrated.

by @hsjobeki; co-authored by @mightyiam

in https://github.com/nix-community/nixdoc/pull/91.

## 2.7.0

- Added support to customise the attribute set prefix, which was previously hardcoded to `lib`.
- Added support to customize the attribute set prefix, which was previously hardcoded to `lib`.
The default is still `lib`, but you can pass `--prefix` now to use something else like `utils`.

By @Janik-Haag in https://github.com/nix-community/nixdoc/pull/97
Expand Down
61 changes: 58 additions & 3 deletions README.md
Expand Up @@ -10,8 +10,57 @@ function set.

## Comment format

Currently, identifiers are included in the documentation if they have
a preceding comment in multiline syntax `/* something */`.
This tool implements a subset of the doc-comment standard specified in [RFC-145/doc-comments](https://github.com/NixOS/rfcs/blob/master/rfcs/0145-doc-strings.md).
But, it is currently limited to generating documentation for statically analyzable attribute paths only.
In the future, it could be the role of a Nix interpreter to obtain the values to be documented and their doc-comments.

It is important to start doc-comments with the additional asterisk (`*`) -> `/**` which renders as a doc-comment.

The content of the doc-comment should be some markdown. ( See [Commonmark](https://spec.commonmark.org/0.30/) specification)

### Example

The following is an example of markdown documentation for new and current users of nixdoc.

> Sidenote: Indentation is automatically detected and should be consistent across the content.
>
> If you are used to multiline-strings (`''`) in nix this should be intuitive to follow.
````nix
{
/**
This function adds two numbers
# Example
```nix
add 4 5
=>
9
```
# Type
```
add :: Number -> Number -> Number
```
# Arguments
- a: The first number
- b: The second number
*/
add = a: b: a + b;
}
````

## Outdated Format (Legacy)

### Comment format

Identifiers are included in the documentation if they have
a preceding comment in multiline syntax `/* something */`. You should consider migrating to the new format described above.

Two special line beginnings are recognised:

Expand All @@ -22,10 +71,16 @@ Two special line beginnings are recognised:
These will result in appropriate elements being inserted into the
output.

## Function arguments
### Function arguments

Function arguments can be documented by prefixing them with a comment:

> Note: This only works in the legacy format and should not be relied on anymore.
>
> See the markdown example above how to write proper documentation.
>
> For multiple reasons we cannot continue this feature.
```
/* This function does the thing a number of times. */
myFunction =
Expand Down
110 changes: 110 additions & 0 deletions src/comment.rs
@@ -0,0 +1,110 @@
use rnix::ast::{self, AstToken};
use rnix::{match_ast, SyntaxNode};
use rowan::ast::AstNode;

/// Implements functions for doc-comments according to rfc145.
pub trait DocComment {
fn doc_text(&self) -> Option<&str>;
}

impl DocComment for ast::Comment {
/// Function returns the contents of the doc-comment, if the [ast::Comment] is a
/// doc-comment, or None otherwise.
///
/// Note: [ast::Comment] holds both the single-line and multiline comment.
///
/// /**{content}*/
/// -> {content}
///
/// It is named `doc_text` to complement [ast::Comment::text].
fn doc_text(&self) -> Option<&str> {
let text = self.syntax().text();
// Check whether this is a doc-comment
if text.starts_with(r#"/**"#) && self.text().starts_with('*') {
self.text().strip_prefix('*')
} else {
None
}
}
}

/// Function retrieves a doc-comment from the [ast::Expr]
///
/// Returns an [Option<String>] of the first suitable doc-comment.
/// Returns [None] in case no suitable comment was found.
///
/// Doc-comments can appear in two places for any expression
///
/// ```nix
/// # (1) directly before the expression (anonymous)
/// /** Doc */
/// bar: bar;
///
/// # (2) when assigning a name.
/// {
/// /** Doc */
/// foo = bar: bar;
/// }
/// ```
///
/// If the doc-comment is not found in place (1) the search continues at place (2)
/// More precisely before the NODE_ATTRPATH_VALUE (ast)
/// If no doc-comment was found in place (1) or (2) this function returns None.
pub fn get_expr_docs(expr: &SyntaxNode) -> Option<String> {
if let Some(doc) = get_doc_comment(expr) {
// Found in place (1)
doc.doc_text().map(|v| v.to_owned())
} else if let Some(ref parent) = expr.parent() {
match_ast! {
match parent {
ast::AttrpathValue(_) => {
if let Some(doc_comment) = get_doc_comment(parent) {
doc_comment.doc_text().map(|v| v.to_owned())
}else{
None
}
},
_ => {
// Yet unhandled ast-nodes
None
}

}
}
// None
} else {
// There is no parent;
// No further places where a doc-comment could be.
None
}
}

/// Looks backwards from the given expression
/// Only whitespace or non-doc-comments are allowed in between an expression and the doc-comment.
/// Any other Node or Token stops the peek.
fn get_doc_comment(expr: &SyntaxNode) -> Option<ast::Comment> {
let mut prev = expr.prev_sibling_or_token();
loop {
match prev {
Some(rnix::NodeOrToken::Token(ref token)) => {
match_ast! { match token {
ast::Whitespace(_) => {
prev = token.prev_sibling_or_token();
},
ast::Comment(it) => {
if it.doc_text().is_some() {
break Some(it);
}else{
//Ignore non-doc comments.
prev = token.prev_sibling_or_token();
}
},
_ => {
break None;
}
}}
}
_ => break None,
};
}
}
104 changes: 104 additions & 0 deletions src/format.rs
@@ -0,0 +1,104 @@
use textwrap::dedent;

/// Ensure all lines in a multi-line doc-comments have the same indentation.
///
/// Consider such a doc comment:
///
/// ```nix
/// {
/// /* foo is
/// the value:
/// 10
/// */
/// foo = 10;
/// }
/// ```
///
/// The parser turns this into:
///
/// ```
/// foo is
/// the value:
/// 10
/// ```
///
///
/// where the first line has no leading indentation, and all other lines have preserved their
/// original indentation.
///
/// What we want instead is:
///
/// ```
/// foo is
/// the value:
/// 10
/// ```
///
/// i.e. we want the whole thing to be dedented. To achieve this, we remove all leading whitespace
/// from the first line, and remove all common whitespace from the rest of the string.
pub fn handle_indentation(raw: &str) -> Option<String> {
let result: String = match raw.split_once('\n') {
Some((first, rest)) => {
format!("{}\n{}", first.trim_start(), dedent(rest))
}
None => raw.into(),
};

Some(result.trim().to_owned()).filter(|s| !s.is_empty())
}

/// Shift down markdown headings
///
/// Performs a line-wise matching to ' # Heading '
///
/// Counts the current numbers of '#' and adds levels: [usize] to them
/// levels := 1; gives
/// '# Heading' -> '## Heading'
///
/// Markdown has 6 levels of headings. Everything beyond that (e.g., H7) may produce unexpected renderings.
/// by default this function makes sure, headings don't exceed the H6 boundary.
/// levels := 2;
/// ...
/// H4 -> H6
/// H6 -> H6
///
pub fn shift_headings(raw: &str, levels: usize) -> String {
let mut result = String::new();
for line in raw.lines() {
if line.trim_start().starts_with('#') {
result.push_str(&format!("{}\n", &handle_heading(line, levels)));
} else {
result.push_str(&format!("{line}\n"));
}
}
result
}

// Dumb heading parser.
pub fn handle_heading(line: &str, levels: usize) -> String {
let chars = line.chars();

let mut leading_trivials: String = String::new();
let mut hashes = String::new();
let mut rest = String::new();
for char in chars {
match char {
' ' | '\t' if hashes.is_empty() => {
// only collect trivial before the initial hash
leading_trivials.push(char)
}
'#' if rest.is_empty() => {
// only collect hashes if no other tokens
hashes.push(char)
}
_ => rest.push(char),
}
}
let new_hashes = match hashes.len() + levels {
// We reached the maximum heading size.
6.. => "#".repeat(6),
_ => "#".repeat(hashes.len() + levels),
};

format!("{leading_trivials}{new_hashes} {rest}")
}

0 comments on commit 490ed95

Please sign in to comment.