1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
/*
* Copyright 2019 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! Types supporting documentation for code written in or for Starlark.
// TODO(nga): document it
#![allow(missing_docs)]
pub mod markdown;
use std::collections::HashMap;
use allocative::Allocative;
use dupe::Dupe;
use itertools::Itertools;
pub use markdown::MarkdownFlavor;
pub use markdown::RenderMarkdown;
use once_cell::sync::Lazy;
use regex::Regex;
use regex::RegexBuilder;
use serde::Serialize;
pub use starlark_derive::StarlarkDocs;
use starlark_map::small_map::SmallMap;
use starlark_syntax::syntax::ast::AstLiteral;
use starlark_syntax::syntax::ast::AstPayload;
use starlark_syntax::syntax::ast::AstStmtP;
use starlark_syntax::syntax::ast::ExprP;
use starlark_syntax::syntax::ast::StmtP;
use crate as starlark;
use crate::codemap::Spanned;
use crate::typing::Ty;
use crate::values::StarlarkValue;
use crate::values::Trace;
use crate::values::Value;
/// There have been bugs around line endings in the textwrap crate. Just join
/// into a single string, and trim the line endings.
fn wrap_trimmed(s: &str, width: usize) -> String {
textwrap::wrap(s, width).join("\n").trim_end().to_owned()
}
/// There have been bugs around line endings in the textwrap crate. Just trim the line endings.
fn indent_trimmed(s: &str, prefix: &str) -> String {
textwrap::indent(s, prefix).trim_end().to_owned()
}
/// The documentation provided by a user for a specific module, object, function, etc.
#[derive(Debug, Clone, PartialEq, Serialize, Trace, Default, Allocative)]
pub struct DocString {
/// The first line of a doc string. This has whitespace trimmed from it.
pub summary: String,
/// The contents of a doc string that follow the summary, and a single blank line.
/// This also has whitespace trimmed from it, and it is dedented.
pub details: Option<String>,
}
impl DocString {
/// Render this docstring as a "starlark" docstring.
fn render_as_code(&self) -> String {
let s = match &self.details {
Some(details) => {
format!("{}\n\n{}", self.summary, details)
}
None => self.summary.clone(),
};
wrap_trimmed(&s, 80)
}
/// Render the docstring as in `render_as_code`, but surround it in triple quotes,
/// a common convention in starlark docstrings.
fn render_as_quoted_code(&self) -> String {
format!("\"\"\"\n{}\n\"\"\"", self.render_as_code())
}
}
/// Controls the formatting to use when parsing `DocString`s from raw docstrings
#[derive(Copy, Clone, Dupe)]
pub enum DocStringKind {
/// Docstrings provided by users in starlark files, following python-y documentation style.
///
/// For functions, they are the piece in `"""` that come right after the `def foo():` line,
/// and they have sections for additional details. An example from a starlark file might be:
///
/// ```starlark
/// """ Module level docs here """
///
/// def some_function(val: "string") -> "string":
/// """ This function takes a string and returns it.
///
/// This is where an explanation might go, but I have none
///
/// Args:
/// val: This is the value that gets returned
///
/// Returns:
/// The original value, because identity functions are fun.
/// ```
Starlark,
/// Docstrings used with `#[starlark_module]` in rust.
///
/// These are the documentation strings prefixed by `///` (like these docs) on
/// `#[starlark_module]`, and the functions / attributes within it. It supports
/// a section `# Arguments`, and `# Returns`, and removes some lines from code
/// blocks that are valid for rustdoc, but not useful for people using these
/// functions via starlark. An example might be something like:
///
/// ```
/// # use starlark::starlark_module;
/// # use starlark::environment::MethodsBuilder;
/// # use starlark::values::Value;
///
/// /// These are where the module / object level docs go
/// #[starlark_module]
/// fn add_some_value(builder: &mut MethodsBuilder) {
/// /// attr1 is an attribute that does nothing interesting.
/// #[starlark(attribute)]
/// fn attr1<'v>(this: Value<'v>) -> anyhow::Result<String> {
/// let _ = this;
/// Ok("attr1".to_owned())
/// }
/// /// Copies a string
/// ///
/// /// This is where details would be, if this were
/// /// a more interesting function.
/// ///
/// /// # Arguments
/// /// * `s`: This is string that is returned.
/// ///
/// /// # Returns
/// /// The a copy of the original string.
/// fn copy_string<'v>(this: Value<'v>, s: &str) -> anyhow::Result<String> {
/// let _ = this;
/// Ok(s.to_owned())
/// }
/// }
/// ```
Rust,
}
impl DocString {
/// Extracts the docstring from a function or module body, iff the first
/// statement is a string literal.
pub(crate) fn extract_raw_starlark_docstring<P: AstPayload>(
body: &AstStmtP<P>,
) -> Option<String> {
if let StmtP::Statements(stmts) = &body.node {
if let Some(Spanned {
node:
StmtP::Expression(Spanned {
node: ExprP::Literal(AstLiteral::String(s)),
..
}),
..
}) = stmts.first()
{
return Some(s.node.to_owned());
}
};
None
}
fn split_summary_details(s: &str) -> Option<(&str, &str)> {
let mut summary_len = 0;
for line in s.split_inclusive('\n') {
if line.trim().is_empty() {
let details_start = summary_len + line.len();
return Some((s[..summary_len].trim(), &s[details_start..]));
} else {
summary_len += line.len();
}
}
None
}
// Remove any newlines (and surrounding whitespace) in the summary, and
// replace them with a single space.
fn normalize_summary(summary: &str) -> String {
let mut res = String::with_capacity(summary.len());
for line in summary.lines() {
if !res.is_empty() {
res.push(' ');
}
res.push_str(line.trim());
}
res
}
/// Do common work to parse a docstring (dedenting, splitting summary and details, etc)
pub fn from_docstring(kind: DocStringKind, user_docstring: &str) -> Option<DocString> {
let trimmed_docs = user_docstring.trim();
if trimmed_docs.is_empty() {
None
} else {
let split: Option<(&str, &str)> = Self::split_summary_details(trimmed_docs);
let (summary, details) = match split {
Some((summary, details)) if !summary.is_empty() && !details.is_empty() => {
// Dedent the details separately so that people can have the summary on the
// same line as the opening quotes, and the details indented on subsequent
// lines.
let details = match kind {
DocStringKind::Starlark => textwrap::dedent(details).trim().to_owned(),
DocStringKind::Rust => {
Self::remove_rust_comments(textwrap::dedent(details).trim())
}
};
(summary, Some(details))
}
_ => (trimmed_docs, None),
};
let summary = Self::normalize_summary(summary);
Some(DocString { summary, details })
}
}
/// Removes rustdoc-style commented out lines from code blocks.
fn remove_rust_comments(details: &str) -> String {
static CODEBLOCK_RE: Lazy<Regex> = Lazy::new(|| {
RegexBuilder::new(r"```(\w*)\n.*?```")
.dot_matches_new_line(true)
.build()
.expect("regex to compile")
});
static COMMENT_RE: Lazy<Regex> = Lazy::new(|| {
RegexBuilder::new(r"^# .*$\n")
.multi_line(true)
.build()
.expect("regex to compile")
});
CODEBLOCK_RE
.replace_all(details, |caps: ®ex::Captures| {
match caps.get(1).expect("language group").as_str() {
"" | "rust" => COMMENT_RE
.replace_all(caps.get(0).expect("$0 to exist").as_str(), "")
.to_string(),
_ => caps.get(0).expect("$0 to exist").as_str().to_owned(),
}
})
.to_string()
}
/// Join lines up, dedent them, and trim them
fn join_and_dedent_lines(lines: &[String]) -> String {
textwrap::dedent(&lines.join("\n")).trim().to_owned()
}
/// Parse the sections out of a docstring's `details` text, and remove the requested sections from the text.
///
/// "sections" are the various things in doc strings like "Arguments:", "Returns:", etc
///
/// # Returns
/// - A new instance of `DocString`, with the requested sections, if found, removed.
/// - A mapping of section name, converted to lower case, to the cleaned up section text
/// i.e. dedented, section header not present, etc for any found sections.
fn parse_and_remove_sections(
self,
kind: DocStringKind,
requested_sections: &[&str],
) -> (Self, HashMap<String, String>) {
let mut sections = HashMap::new();
let mut finish_section =
|current_section: &mut Option<String>, current_section_text: &mut Vec<String>| {
if let Some(s) = current_section.take() {
sections.insert(s, DocString::join_and_dedent_lines(current_section_text));
current_section_text.clear();
}
};
static STARLARK_SECTION_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^([\w -]+):\s*$").unwrap());
static STARLARK_INDENTED_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(?:\s|$)").unwrap());
static RUST_SECTION_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^# ([\w -]+)\s*$").unwrap());
static RUST_INDENTED_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^.*").unwrap());
let (section_re, indented_re) = match kind {
DocStringKind::Starlark => (&STARLARK_SECTION_RE, &STARLARK_INDENTED_RE),
DocStringKind::Rust => (&RUST_SECTION_RE, &RUST_INDENTED_RE),
};
if let Some(details) = self.details {
let mut new_details = vec![];
let mut current_section = None;
let mut current_section_text = vec![];
for line in details.lines() {
if let Some(matches) = section_re.captures(line) {
finish_section(&mut current_section, &mut current_section_text);
let found_section = matches.get(1).unwrap().as_str().to_ascii_lowercase();
if requested_sections.contains(&found_section.as_str()) {
current_section = Some(found_section);
} else {
new_details.push(line.to_owned());
}
} else if current_section.is_some() && indented_re.is_match(line) {
current_section_text.push(line.to_owned());
} else {
new_details.push(line.to_owned());
finish_section(&mut current_section, &mut current_section_text);
}
}
finish_section(&mut current_section, &mut current_section_text);
let joined_details = new_details.join("\n").trim().to_owned();
let details = match joined_details.is_empty() {
true => None,
false => Some(joined_details),
};
(
Self {
summary: self.summary,
details,
},
sections,
)
} else {
(self, sections)
}
}
}
/// The file a symbol resides in, and if available its location within that file.
#[derive(Debug, Clone, PartialEq, Serialize, Default)]
pub struct Location {
/// `path` is a string that can be passed into `load()` statements.
pub path: String,
}
/// The main identifier for a symbol.
#[derive(Debug, Clone, PartialEq, Serialize, Default)]
pub struct Identifier {
/// The name of the symbol (e.g. the function name, a name or path for a module, etc).
pub name: String,
/// Where the symbol is located, or absent if it is a built-in symbol.
pub location: Option<Location>,
}
/// Documents a full module.
#[derive(Debug, Clone, PartialEq, Serialize, Default, Allocative)]
pub struct DocModule {
/// In general, this should be the first statement of a loaded file, if that statement is
/// a string literal.
pub docs: Option<DocString>,
/// A mapping of top level symbols to their documentation, if any.
pub members: SmallMap<String, DocMember>,
}
impl DocModule {
pub(crate) fn render_as_code(&self) -> String {
let mut res = self
.docs
.as_ref()
.map(DocString::render_as_quoted_code)
.unwrap_or_default();
for (k, v) in &self.members {
res.push('\n');
res.push_str(&(Doc::named_item(k.clone(), v.clone().to_doc_item())).render_as_code());
res.push('\n');
}
res
}
}
/// Documents a single function.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Allocative)]
pub struct DocFunction {
/// Documentation for the function. If parsed, this should generally be the first statement
/// of a function's body if that statement is a string literal. Any sections like "Args:",
/// "Returns", etc are kept intact. It is up to the consumer to remove these sections if
/// they are present.
pub docs: Option<DocString>,
/// The parameters that this function takes. Docs for these parameters should generally be
/// extracted from the main docstring's details.
pub params: Vec<DocParam>,
/// Details about what this function returns.
pub ret: DocReturn,
/// Does this function act as type?
pub as_type: Option<Ty>,
}
impl DocFunction {
fn starlark_docstring(&self) -> Option<String> {
let mut docs = String::new();
if let Some(main_docs) = self.docs.as_ref().map(DocString::render_as_code) {
docs.push_str(&main_docs);
}
let args_indentation_count = self
.params
.iter()
.map(|p| match p {
DocParam::NoArgs | DocParam::OnlyPosBefore => 0,
DocParam::Arg { name, .. }
| DocParam::Args { name, .. }
| DocParam::Kwargs { name, .. } => name.len() + 2,
})
.max()
.unwrap_or_default();
let args_indentation = " ".repeat(args_indentation_count);
let args_docs = self
.params
.iter()
.filter_map(|p| p.starlark_docstring(&args_indentation))
.join("\n");
if !args_docs.is_empty() {
let indented = indent_trimmed(&args_docs, " ");
docs.push_str(&format!("\n\nArgs:\n{}", indented));
}
if let Some(ret_docs) = self.ret.starlark_docstring() {
let indented = indent_trimmed(&ret_docs, " ");
docs.push_str(&format!("\n\nRet:\n{}", indented));
}
if docs.is_empty() {
None
} else {
Some(indent_trimmed(
&format!("\"\"\"\n{}\n\"\"\"", docs.trim_start()),
" ",
))
}
}
pub(crate) fn render_as_code(&self, name: &str) -> String {
let params: Vec<_> = self.params.iter().map(DocParam::render_as_code).collect();
let spacer_len = if params.is_empty() {
0
} else {
(params.len() - 1) * 2
};
let params_len = params.iter().map(|a| a.len()).sum::<usize>() + spacer_len;
let params = if params_len > 60 {
format!("(\n{}\n)", indent_trimmed(¶ms.join(",\n"), " "))
} else {
format!("({})", params.join(", "))
};
let docstring = self
.starlark_docstring()
.map(|mut ds| {
ds.push('\n');
ds
})
.unwrap_or_default();
let ret = Some(&self.ret.typ)
.filter(|t| t != &&Ty::any())
.map(|t| format!(" -> {}", t))
.unwrap_or_default();
format!("def {}{}{}:\n{} pass", name, params, ret, docstring)
}
/// Used by LSP.
pub fn find_param_with_name(&self, param_name: &str) -> Option<&DocParam> {
self.params.iter().find(|p| match p {
DocParam::Arg { name, .. }
| DocParam::Args { name, .. }
| DocParam::Kwargs { name, .. }
if name == param_name =>
{
true
}
_ => false,
})
}
/// Parses function documentation out of a docstring
///
/// # Arguments
/// * `kind`: The kind of docstring. This determines the formatting that is parsed.
/// * `params`: The parameters of the function.
/// * `return_type`: The return type. This is pulled from typing info / directly from users,
/// so it cannot be inferred generically.
/// * `raw_docstring`: The raw docstring to be parsed and potentially modified,
/// removing the sections detailing arguments and return values.
/// The format is determined by `kind`.
pub fn from_docstring(
kind: DocStringKind,
mut params: Vec<DocParam>,
return_type: Ty,
raw_docstring: Option<&str>,
as_type: Option<Ty>,
) -> Self {
match raw_docstring.and_then(|raw| DocString::from_docstring(kind, raw)) {
Some(ds) => {
let (function_docstring, sections) =
ds.parse_and_remove_sections(kind, &["arguments", "args", "returns", "return"]);
match sections.get("arguments").or_else(|| sections.get("args")) {
Some(args) => {
let entries = Self::parse_params(kind, args);
for x in &mut params {
match x {
DocParam::Arg { name, docs, .. }
| DocParam::Args { name, docs, .. }
| DocParam::Kwargs { name, docs, .. } => match entries.get(name) {
Some(raw) => *docs = DocString::from_docstring(kind, raw),
_ => (),
},
_ => (),
}
}
}
_ => (),
}
let return_docs = sections
.get("return")
.or_else(|| sections.get("returns"))
.and_then(|raw| DocString::from_docstring(kind, raw));
DocFunction {
docs: Some(function_docstring),
params,
ret: DocReturn {
docs: return_docs,
typ: return_type,
},
as_type,
}
}
None => DocFunction {
docs: None,
params,
ret: DocReturn {
docs: None,
typ: return_type,
},
as_type,
},
}
}
/// Parse out parameter docs from an "Args:" section of a docstring
///
/// `args_section` should be dedented, and generally should just be the `args` key of
/// the `DocString::parse_and_remove_sections()` function call. This is done as a
/// separate function to reduce the number of times that sections are parsed out of
/// docstring (e.g. if a user wants both the `Args:` and `Returns:` sections)
fn parse_params(kind: DocStringKind, args_section: &str) -> HashMap<String, String> {
static STARLARK_ARG_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(\*{0,2}\w+):\s*(.*)").unwrap());
static RUST_ARG_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(?:\* )?`(\w+)`:?\s*(.*)").unwrap());
static INDENTED_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(?:\s|$)").unwrap());
let arg_re = match kind {
DocStringKind::Starlark => &STARLARK_ARG_RE,
DocStringKind::Rust => &RUST_ARG_RE,
};
let mut ret = HashMap::new();
let mut current_arg = None;
let mut current_text = vec![];
for line in args_section.lines() {
if let Some(matches) = arg_re.captures(line) {
if let Some(a) = current_arg.take() {
ret.insert(a, DocString::join_and_dedent_lines(¤t_text));
}
current_arg = Some(matches.get(1).unwrap().as_str().to_owned());
let doc_match = matches.get(2).unwrap();
current_text = vec![format!(
"{}{}",
" ".repeat(doc_match.start()),
doc_match.as_str()
)];
} else if current_arg.is_some() && INDENTED_RE.is_match(line) {
current_text.push(line.to_owned());
}
}
if let Some(a) = current_arg.take() {
ret.insert(a, DocString::join_and_dedent_lines(¤t_text));
}
ret
}
}
/// A single parameter of a function.
#[derive(Debug, Clone, PartialEq, Serialize, Allocative)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DocParam {
/// A regular parameter that may or may not have a default value.
Arg {
name: String,
docs: Option<DocString>,
#[serde(rename = "type")]
typ: Ty,
/// If present, this parameter has a default value. This is the `repr()` of that value.
default_value: Option<String>,
},
/// Represents the "*" argument.
NoArgs,
/// Represents the "/" argument from [PEP 570](https://peps.python.org/pep-0570/).
OnlyPosBefore,
/// Represents the "*args" style of argument.
Args {
name: String,
docs: Option<DocString>,
#[serde(rename = "type")]
typ: Ty,
},
/// Represents the "**kwargs" style of argument.
Kwargs {
name: String,
docs: Option<DocString>,
#[serde(rename = "type")]
typ: Ty,
},
}
impl DocParam {
fn starlark_docstring(&self, max_indentation: &str) -> Option<String> {
let (name, docs) = match self {
DocParam::Arg { name, docs, .. } => Some((name, docs)),
DocParam::NoArgs | DocParam::OnlyPosBefore => None,
DocParam::Args { name, docs, .. } => Some((name, docs)),
DocParam::Kwargs { name, docs, .. } => Some((name, docs)),
}?;
let rendered_docs = docs.as_ref()?.render_as_code();
let mut indented = indent_trimmed(&rendered_docs, max_indentation);
indented.replace_range(..name.len() + 2, &format!("{}: ", name));
Some(indented)
}
fn render_as_code(&self) -> String {
match self {
DocParam::Arg {
name,
typ,
default_value,
..
} => match (typ, default_value.as_ref()) {
(t, Some(default)) if t.is_any() => format!("{} = {}", name, default),
(t, None) if t.is_any() => name.clone(),
(t, Some(default)) => format!("{}: {} = {}", name, t, default),
(t, None) => format!("{}: {}", name, t),
},
DocParam::NoArgs => "*".to_owned(),
DocParam::OnlyPosBefore => "/".to_owned(),
DocParam::Args { name, typ, .. } | DocParam::Kwargs { name, typ, .. } => match typ {
t if t.is_any() => name.clone(),
typ => format!("{}: {}", name, typ),
},
}
}
}
/// Details about the return value of a function.
#[derive(Debug, Clone, PartialEq, Serialize, Allocative)]
pub struct DocReturn {
/// Extra semantic details around the returned value's meaning.
pub docs: Option<DocString>,
#[serde(rename = "type")]
pub typ: Ty,
}
impl Default for DocReturn {
fn default() -> Self {
DocReturn {
docs: None,
typ: Ty::any(),
}
}
}
impl DocReturn {
fn starlark_docstring(&self) -> Option<String> {
self.docs.as_ref().map(DocString::render_as_code)
}
}
/// A single property of an object. These are explicitly not functions (see [`DocMember`]).
#[derive(Debug, Clone, PartialEq, Serialize, Allocative)]
pub struct DocProperty {
pub docs: Option<DocString>,
#[serde(rename = "type")]
pub typ: Ty,
}
impl DocProperty {
pub(crate) fn render_as_code(&self, name: &str) -> String {
match (
&self.typ,
self.docs.as_ref().map(DocString::render_as_quoted_code),
) {
// TODO(nmj): The starlark syntax needs to be updated to support type
// annotations on values as python does. Afterward, use these
// format strings.
// (Some(t), Some(ds)) => {
// format!("{}\n_{}: {} = None", ds, name, t.raw_type)
// }
// (Some(t), None) => format!(r#"_{}: {} = None"#, name, t.raw_type),
(t, Some(ds)) if t.is_any() => format!("{}\n_{} = None", ds, name),
(t, None) if t.is_any() => format!("_{} = None", name),
(t, Some(ds)) => {
format!("{}\n# type: {}\n_{} = None", ds, t, name)
}
(t, None) => format!("# type: {}\n_{} = None", t, name),
}
}
}
/// A named member of an object.
#[derive(Debug, Clone, PartialEq, Serialize, Allocative)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DocMember {
Property(DocProperty),
Function(DocFunction),
}
impl DocMember {
pub(crate) fn from_value(value: Value) -> Self {
// If we have a value which is a complex type, the right type to put in the docs is not the type
// it represents, but it's just a property we should point at
match value.documentation() {
Some(DocItem::Function(x)) => DocMember::Function(x),
Some(DocItem::Property(x)) => DocMember::Property(x),
_ => DocMember::Property(DocProperty {
docs: None,
typ: value.get_type_starlark_repr(),
}),
}
}
pub fn to_doc_item(self) -> DocItem {
match self {
DocMember::Property(x) => DocItem::Property(x),
DocMember::Function(x) => DocItem::Function(x),
}
}
}
/// An object with named functions/properties.
#[derive(Debug, Clone, PartialEq, Serialize, Default, Allocative)]
pub struct DocObject {
pub docs: Option<DocString>,
/// Name and details of each member of this object.
pub members: SmallMap<String, DocMember>,
}
impl DocObject {
pub(crate) fn render_as_code(&self, name: &str) -> String {
let summary = self
.docs
.as_ref()
.map(|ds| {
let mut s = ds.render_as_quoted_code();
s.push('\n');
s
})
.unwrap_or_default();
let member_docs = self
.members
.iter()
.map(|(name, member)| match member {
DocMember::Property(p) => p.render_as_code(name),
DocMember::Function(f) => f.render_as_code(&format!("_{}", name)),
})
.join("\n\n");
let exported_struct_members = self
.members
.iter()
.map(|(name, _)| format!(" {} = _{},", name, name))
.join("\n");
let exported_struct = if !exported_struct_members.is_empty() {
format!(
"{}{} = struct(\n{}\n)",
summary, name, exported_struct_members
)
} else {
String::new()
};
format!("{}\n\n{}", member_docs, exported_struct)
.trim()
.to_owned()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Allocative)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DocItem {
Module(DocModule),
Object(DocObject),
Function(DocFunction),
Property(DocProperty),
}
impl DocItem {
/// Get the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_string(&self) -> Option<&DocString> {
match self {
DocItem::Module(m) => m.docs.as_ref(),
DocItem::Object(o) => o.docs.as_ref(),
DocItem::Function(f) => f.docs.as_ref(),
DocItem::Property(p) => p.docs.as_ref(),
}
}
/// Get the summary of the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_summary(&self) -> Option<&str> {
self.get_doc_string().map(|ds| ds.summary.as_str())
}
}
impl DocMember {
/// Get the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_string(&self) -> Option<&DocString> {
match self {
DocMember::Function(f) => f.docs.as_ref(),
DocMember::Property(p) => p.docs.as_ref(),
}
}
/// Get the summary of the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_summary(&self) -> Option<&str> {
self.get_doc_string().map(|ds| ds.summary.as_str())
}
}
impl DocParam {
/// Get the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_string(&self) -> Option<&DocString> {
match self {
DocParam::Arg { docs, .. }
| DocParam::Args { docs, .. }
| DocParam::Kwargs { docs, .. } => docs.as_ref(),
_ => None,
}
}
/// Get the summary of the underlying [`DocString`] for this item, if it exists.
pub fn get_doc_summary(&self) -> Option<&str> {
self.get_doc_string().map(|ds| ds.summary.as_str())
}
}
/// The main structure that represents the documentation for a given symbol / module.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Doc {
pub id: Identifier,
pub item: DocItem,
/// Custom key-value pairs that are not interpreted directly by starlark, and can be
/// used as arbitrary data for documentation tooling.
pub custom_attrs: HashMap<String, String>,
}
impl Doc {
pub fn named_item(name: String, item: DocItem) -> Self {
Doc {
id: Identifier {
name,
location: None,
},
item,
custom_attrs: HashMap::new(),
}
}
/// Render a starlark code representation of this documentation object.
///
/// Function bodies for these consist of a single "pass" statement, and objects
/// are represented as structs.
pub fn render_as_code(&self) -> String {
match &self.item {
DocItem::Module(m) => m.render_as_code(),
DocItem::Object(o) => o.render_as_code(&self.id.name),
DocItem::Function(f) => f.render_as_code(&self.id.name),
DocItem::Property(p) => p.render_as_code(&self.id.name),
}
}
}
/// Render a series of [`Doc`] objects into a "starlark" file.
///
/// Function bodies for these consist of a single "pass" statement, and objects
/// are represented as structs.
///
/// The returned array may not be in the same order as the originally provided docs.
/// They are in the order that they should appear in the rendered starlark file.
pub fn render_docs_as_code(docs: &[Doc]) -> String {
let (modules, non_modules): (Vec<_>, Vec<_>) = docs
.iter()
.partition(|d| matches!(d.item, DocItem::Module(_)));
modules
.into_iter()
.chain(non_modules)
.map(|d| d.render_as_code())
.join("\n\n")
}
/// Get documentation for all items registered with `#[derive(StarlarkDocs)]`
///
/// Note: Because `StarlarkDocs` uses the inventory crate under the hood, in statically linked
/// binaries, documentation from all compiled crates in the binary will be included.
///
/// For dynamically linked binaries, documentation will only be able to retrieved after the crate's
/// library is `dlopen()`ed.
pub fn get_registered_starlark_docs() -> Vec<Doc> {
inventory::iter::<RegisteredDoc>
.into_iter()
.filter_map(|d| (d.getter)())
.collect()
}
#[doc(hidden)]
pub struct RegisteredDoc {
pub getter: fn() -> Option<Doc>,
}
inventory::collect!(RegisteredDoc);
impl RegisteredDoc {
/// This function is called from generated code.
pub fn for_type<'v, T: StarlarkValue<'v>>(custom_attrs: &[(&str, &str)]) -> Option<Doc> {
let name = T::TYPE.to_owned();
let id = Identifier {
name,
location: None,
};
let item = DocItem::Object(T::get_methods()?.documentation());
let custom_attrs = custom_attrs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect();
Some(Doc {
id,
item,
custom_attrs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_starlark_docstring() {
assert_eq!(
DocString::from_docstring(DocStringKind::Starlark, " "),
None
);
assert_eq!(
DocString::from_docstring(
DocStringKind::Starlark,
" \n\nThis should be the summary\n\n"
),
Some(DocString {
summary: "This should be the summary".to_owned(),
details: None,
})
);
assert_eq!(
DocString::from_docstring(
DocStringKind::Starlark,
" \n\nThis should be the summary\n\n "
),
Some(DocString {
summary: "This should be the summary".to_owned(),
details: None,
})
);
assert_eq!(
DocString::from_docstring(
DocStringKind::Starlark,
"Summary line here\n \nDetails after some spaces\n\nand some more newlines"
),
Some(DocString {
summary: "Summary line here".to_owned(),
details: Some("Details after some spaces\n\nand some more newlines".to_owned()),
})
);
assert_eq!(
DocString::from_docstring(
DocStringKind::Starlark,
r#"
This is the summary.
It has multiple lines and some spaces, and should be collapsed
This should be a multiline set of details.
It should be:
- Dedented
- Trimmed
- Split properly from the summary
"#
),
Some(DocString {
summary: "This is the summary. It has multiple lines and some spaces, and should be collapsed".to_owned(),
details: Some(
concat!(
"This should be a multiline set of details.\n",
"It should be:\n",
" - Dedented\n",
" - Trimmed\n",
" - Split properly from the summary"
)
.to_owned()
),
})
);
assert_eq!(
DocString::from_docstring(
DocStringKind::Starlark,
r#"This is a summary line that is not dedented like the 'details'
Typing the first line right after the """ in python docstrings is common,
while putting the rest of the docstring indented. Just support both so it
doesn't surprise anyone.
"#
),
Some(DocString {
summary: "This is a summary line that is not dedented like the 'details'"
.to_owned(),
details: Some(
concat!(
"Typing the first line right after the \"\"\" in python docstrings is common,\n",
"while putting the rest of the docstring indented. Just support both so it\n",
"doesn't surprise anyone."
)
.to_owned()
),
})
);
}
#[test]
fn parses_rust_docstring() {
let raw = r#"
This is the summary line
that sometimes is split on two lines
This is the second part. It has some code blocks
```
# foo() {
"bar"
# }
```
```python
# This is a python comment. Leave it be
print(1)
```
```rust
# other_foo() {
"other_bar"
# }
```
"#;
let parsed = DocString::from_docstring(DocStringKind::Rust, raw).unwrap();
assert_eq!(
"This is the summary line that sometimes is split on two lines",
parsed.summary
);
assert_eq!(
concat!(
"This is the second part. It has some code blocks\n\n",
"```\n",
"\"bar\"\n",
"```\n\n",
"```python\n",
"# This is a python comment. Leave it be\n",
"print(1)\n",
"```\n\n",
"```rust\n",
"\"other_bar\"",
"\n```"
),
parsed.details.unwrap()
);
}
#[test]
fn parses_and_removes_sections_from_starlark_docstring() {
let raw_docs = r#"This is an example docstring
We have some details up here that should not be parsed
Some empty section:
Example:
First line of the section
A newline with no space after it before the second one,
and a third that's indented further.
This is not in the example section
Last:
This is something in the last section
"#;
let expected_docstring = DocString::from_docstring(
DocStringKind::Starlark,
r#"This is an example docstring
We have some details up here that should not be parsed
Some empty section:
This is not in the example section
Last:
This is something in the last section
"#,
)
.unwrap();
let expected_sections = HashMap::from([(
"example".to_owned(),
concat!(
"First line of the section\n\n",
"A newline with no space after it before the second one,\n",
" and a third that's indented further."
)
.to_owned(),
)]);
let ds = DocString::from_docstring(DocStringKind::Starlark, raw_docs).unwrap();
let (new_ds, sections) =
ds.parse_and_remove_sections(DocStringKind::Starlark, &["example"]);
assert_eq!(new_ds, expected_docstring);
assert_eq!(sections, expected_sections);
}
#[test]
fn parses_and_removes_sections_from_rust_docstring() {
let raw_docs = r#"This is an example docstring
We have some details up here that should not be parsed
# Some Section
```
# This is a commented out line in a codeblock
fn some_func() {}
```
# Example
First line of the section
Note that, unlike starlark doc strings,
we don't require indentation. The end of a
section is either a new section appearing,
or the end of the string.
# Last
This is something in the last section
"#;
let expected_docstring = DocString::from_docstring(
DocStringKind::Rust,
r#"This is an example docstring
We have some details up here that should not be parsed
# Some Section
```
fn some_func() {}
```
# Last
This is something in the last section
"#,
)
.unwrap();
let expected_sections = HashMap::from([(
"example".to_owned(),
concat!(
"First line of the section\n\n",
"Note that, unlike starlark doc strings,\n",
"we don't require indentation. The end of a\n",
"section is either a new section appearing,\n",
"or the end of the string.",
)
.to_owned(),
)]);
let ds = DocString::from_docstring(DocStringKind::Rust, raw_docs).unwrap();
let (new_ds, sections) = ds.parse_and_remove_sections(DocStringKind::Rust, &["example"]);
assert_eq!(new_ds, expected_docstring);
assert_eq!(sections, expected_sections);
}
fn arg(name: &str) -> DocParam {
DocParam::Arg {
name: name.to_owned(),
docs: None,
typ: Ty::any(),
default_value: None,
}
}
#[test]
fn parses_starlark_function_docstring() {
let docstring = r#"This is an example docstring
Details here
Args:
arg_foo: The argument named foo
arg_bar: The argument named bar. It has
a longer doc string that spans
over three lines
*args: Docs for args
**kwargs: Docs for kwargs
Returns:
A value
"#;
let kind = DocStringKind::Starlark;
let return_type = Ty::int();
let expected = DocFunction {
docs: DocString::from_docstring(kind, "This is an example docstring\n\nDetails here"),
params: vec![
DocParam::Arg {
name: "**kwargs".to_owned(),
docs: DocString::from_docstring(kind, "Docs for kwargs"),
typ: Ty::any(),
default_value: None,
},
DocParam::Arg {
name: "*args".to_owned(),
docs: DocString::from_docstring(kind, "Docs for args"),
typ: Ty::any(),
default_value: None,
},
DocParam::Arg {
name: "arg_bar".to_owned(),
docs: DocString::from_docstring(
kind,
concat!(
"The argument named bar. It has\n",
"a longer doc string that spans\n",
"over three lines"
),
),
typ: Ty::any(),
default_value: None,
},
DocParam::Arg {
name: "arg_foo".to_owned(),
docs: DocString::from_docstring(kind, "The argument named foo"),
typ: Ty::any(),
default_value: None,
},
],
ret: DocReturn {
docs: DocString::from_docstring(kind, "A value"),
typ: return_type.clone(),
},
as_type: None,
};
let function_docs = DocFunction::from_docstring(
kind,
vec![
arg("**kwargs"),
arg("*args"),
arg("arg_bar"),
arg("arg_foo"),
],
return_type,
Some(docstring),
None,
);
assert_eq!(expected, function_docs);
}
#[test]
fn parses_rust_function_docstring() {
let docstring = r#"This is an example docstring
Details here
# Arguments
* `arg_foo`: The argument named foo
`arg_bar`: The argument named bar. It has
a longer doc string that spans
over three lines
# Returns
A value
"#;
let kind = DocStringKind::Rust;
let return_type = Ty::int();
let expected = DocFunction {
docs: DocString::from_docstring(kind, "This is an example docstring\n\nDetails here"),
params: vec![
DocParam::Arg {
name: "arg_bar".to_owned(),
docs: DocString::from_docstring(
kind,
concat!(
"The argument named bar. It has\n",
"a longer doc string that spans\n",
"over three lines"
),
),
typ: Ty::any(),
default_value: None,
},
DocParam::Arg {
name: "arg_foo".to_owned(),
docs: DocString::from_docstring(kind, "The argument named foo"),
typ: Ty::any(),
default_value: None,
},
],
ret: DocReturn {
docs: DocString::from_docstring(kind, "A value"),
typ: return_type.clone(),
},
as_type: None,
};
let function_docs = DocFunction::from_docstring(
kind,
vec![arg("arg_bar"), arg("arg_foo")],
return_type,
Some(docstring),
None,
);
assert_eq!(expected, function_docs);
}
}