interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / requirements_extract.rs

2796 lines · 109530 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! | `<min bound> N <noun> and|or|but <bound> M` (second noun left out, e.g. `at least 20 lines and no more than 40`) | the second bound is read with the earlier noun (`MaxLines(40)`); with no clear earlier noun (or no earlier count at all), or a direction the noun does not support (`at least 3 paragraphs and no more than 5`), it is UNCERTAIN, never dropped (#344) |
17//! Reading the requirements out of a goal (see `requirements` for the model).
18//!
19//! `analyze` is rule based and deterministic. It returns the requirements it
20//! recognized AND the spans of goal text that look like explicit measurable
21//! requirements but could not be interpreted reliably (`Extraction::uncertain`).
22//! A caller must refuse a task with uncertain spans: uncertainty is never
23//! treated as satisfied.
24//!
25//! ## Recognized wordings (case-insensitive; trailing punctuation on a word is ignored)
26//!
27//! | goal wording | requirement |
28//! |---|---|
29//! | `at least / no fewer than / no less than / not fewer than / a minimum of / minimum of / min N <noun>`, `N or more <noun>`, `N+ <noun>` | `MinX(N)` |
30//! | `at most / no more than / not more than / a maximum of / maximum of / max / up to N <noun>`, `N or fewer|less <noun>` | `MaxX(N)` |
31//! | `more than N <noun>`, `fewer|less than N <noun>` | `MinX(N+1)`, `MaxX(N-1)` |
32//! | `under|below N words|lines`, `within N words|lines` (only these two nouns; `under three sections`, `under 80 characters` stay UNCERTAIN) | `MaxX(N-1)`, `MaxX(N)` (sc#383) |
33//! | `N <noun> or more|fewer|less`, `N <noun> minimum|maximum`, `no longer|shorter than N <noun>` | `MinX(N)` or `MaxX(N)` |
34//! | `<noun>` = `lines` (also `non-empty|nonempty|non-blank lines`: lines are counted non-empty anyway), `words`; `items`, `steps`, `sections`, `headings`, `questions`, `paragraphs` (Min only; singular too) | lines, words, list items, numbered steps, headings, questions, paragraphs (`MinParagraphs`: runs of prose lines, see `requirements::count_paragraphs`) |
35//! | `N sentences in|per|for|within every|each section` (or `in every section, ... N sentences`) | `MinSentencesPerSection(N)` |
36//! | `a one-sentence|single-sentence X`, `a single sentence`, `just|only|exactly one sentence` (the only such phrase; no part of the file, edit or addition named in the goal) | `SingleSentence` |
37//! | `containing|with [just|only] one line that says|reads "S"` / `one line saying|reading "S"` | `AddedLines` exactly 1 and `RequiredPhrases([S])` (a final `.` `!` `?` inside quotes that end the goal sentence is not part of S). UNQUOTED text there (also after a destination, `one line to a.md saying S`) is read only as one to three plain words running to the end of the sentence, optionally before one destination file (`saying hello to a.md`); a pronoun or vague word, a joiner (`and then`), an instruction verb or a preposition makes it UNCERTAIN, never dropped (sc#349) |
38//! | `sections|headings titled|named|called A, B and C`, `sections: A, B and C`; with quoted titles also `section(s) is|are titled "A"` and `[one] section(s) must|should|will|shall|can be titled "A"` | `RequiredHeadings` (a count before the noun must equal the number of titles; `organise it under three sections titled ...` is read the same). The is/are/be forms stay UNCERTAIN after `each every all any` or with `if unless optionally optional may might when whenever perhaps maybe` in the clause |
39//! | `between N and M lines|words` (N <= M) | `MinX(N)` and `MaxX(M)`, inclusive. Other nouns, `from N to M`, ranges like `2-3`, `... or so`, and a range on a part of the document (a countable noun or `gap space distance` right before `between`, or `each every per` within three words) stay UNCERTAIN |
40//! | `covers|covering A, B and C` (and `to|should|must|will|can cover ...`) | `RequiredTopics` |
41//! | `[must|...] cover|covers|covering N topics: a, b and c` (N equals the list, which ends with the item after its `and`/`or`); a later `... form ... for example X or Y for the first|second|...|last [one]` adds the named forms the word-form rule does not already accept, as `topic (or X)` | `RequiredTopics` |
42//! | `include|contain|use|mention the [exact|following|specific|same] word(s)|term(s) X, Y` or `"X", "Y"`, optionally followed by `somewhere|anywhere in it|in the text|file|document|list` (a place that is the whole document; any other place, a choice (`or`), or a count or scope after the list is UNCERTAIN) | `RequiredWords` |
43//! | `make sure|be sure|ensure|check that the word(s)|term(s) X and Y [both|all|each] appear|occur|show up|are used|are included|are present [somewhere in it]` | `RequiredWords`; a negator, another verb, a narrower place, a choice (`or`) or a count after it is UNCERTAIN |
44//! | `must|should|will|shall|to|also name|mention A, B and C [by name]` where every item is one capitalised word | `RequiredWords` (names); a list mixing names and other words, a choice (`or`), a count or scope after it, or a title with a period (`Dr. Smith`) is UNCERTAIN; a list without names (`the file README.md`, `2024`, `the Smith family`) stays silent |
45//! | `include|contain|use|mention the phrase "X"` / `the phrases "X", "Y"` | `RequiredPhrases` |
46//! | `add|append|insert|with N line(s)`, `exactly N lines` after such a verb, `a N-line <thing>` after a verb | `AddedLines` exactly N |
47//! | `write|put|create|draft|compose|produce|generate N line(s)` | `AddedLines` at least N |
48//! | `<bound> N lines is|are needed|required|necessary` (a trailing status word) | the same as the bound without it |
49//! | `... section titled "T" that holds at least N words of plain text`, `the last section ... N words of plain text` | `SectionMinWords` |
50//! | `N level-two|level-2|second-level|h2 sections titled A, B and C` | `LevelHeadings` (those headings at that level; extra headings of the level are allowed) |
51//! | `start|begin|open with a [markdown] [level-N] heading [line]`, then the end of the clause or `that begins|starts with "# "` (quoted, 1 to 6 `#` and one space) | `FirstLineHeading` (the first line of the file is that heading; a marker fixes the level). Negated, emphasised, qualified or unquoted forms, and any other heading wording after `start with a`, are UNCERTAIN |
52//! | `include|add|put|provide N [separate] fenced code examples|blocks`, or a bound cue before N | `MinItems(CodeBlocks)` |
53//! | `<min bound> N of them|these|those [items|lines|entries]` right after `lines [that] starting|beginning|starts|begins with "P"` in the same sentence (exactly one quoted prefix; singular `line` only after `every|each`; at most four joining words such as `and I want` between the quote and the bound) | `MinPrefixedLines` (at least N lines, outside fenced code, whose text after any indentation starts with exactly `P`). Without that referent, with a negator or a per-section word (`per section heading chapter part`) earlier in the sentence, with another condition after the quote (`and ending with ...`), an upper bound, or no bound cue, the count is UNCERTAIN; so is `N or more of them` |
54//!
55//! Bare line counts. The VERB decides the reading, no task wording is built in. An
56//! edit (the goal names an existing file) is judged on the diff between that file
57//! and the exact proposed bytes (non-empty lines of the proposal that are not in
58//! the longest common subsequence with the file's non-empty lines); a new file
59//! counts as an edit of the empty file. `add 2 lines` therefore means exactly two
60//! non-empty lines were added; `write 20 lines` at least twenty. The count must end
61//! its clause or be followed by `to in into at for about on saying describing giving
62//! listing ...`; `3 lines of context`, `10 lines per section` stay UNCERTAIN.
63//! "N-sentence" is NOT read: a sentence count over a whole document cannot be
64//! verified reliably (headings, lists, abbreviations), so such a goal is UNCERTAIN
65//! and refused. The one exception (sc#336) is a file of one sentence: `a
66//! one-sentence|single-sentence X`, `a single sentence`, `just|only|exactly one
67//! sentence`, is `SingleSentence` when it is the goal's only such phrase and
68//! nothing anywhere in the goal names a part of the file (`each every per
69//! paragraph line section top title ...`) or an edit or addition (`add append
70//! insert prepend update replace rewrite put ...`); `one-sentence` needs `a`/`an`.
71//! A quoted `"S"` after `one line that says|reads|saying|reading` must be read
72//! whole: it closes the goal, or is followed by `.` `!` `?` or by a new
73//! capitalised sentence after a final `.` `!` `?`; otherwise (unclosed, empty,
74//! `"S" in bold`, `"S" and another line`) it is UNCERTAIN. `N words of plain text` without a named section
75//! (`section titled "T"`, `the last section`) is a count over an unknown scope and
76//! is UNCERTAIN. `cover three topics: a, b and c` is read only when the count equals
77//! the list (sc#332); otherwise it is UNCERTAIN.
78//! "N lines at least" is a lower bound; "a single line" is exactly one. Left UNCERTAIN on
79//! purpose: ranges ("2-3 lines"), "a dozen lines", "three-plus sections", "line count at
80//! least 40", counts of shell commands or snippets, level-two headings given as a bare
81//! list, and a section title that itself holds a count. "a couple of", "a few",
82//! "several" and "add a line" (no number) state no number and stay silent.
83//! The machine goal of an approved run ("apply approved proposal for <path> ...")
84//! is never analysed; the goal bound into the approval is.
85//!
86//! `N` is digits or a number word (`one` to `twenty`, tens up to `hundred`,
87//! `twenty-five`), at least 1.
88//!
89//! Safety net: after the recognizers, any number (digits or one..hundred) within three
90//! words of a countable document noun (line, word, sentence, paragraph, section,
91//! heading, bullet, point, item, step, block, example, question, topic, character, page,
92//! table, row, column), a quantity cue (`twice minimum maximum limit or more/fewer no
93//! longer than`) near such a noun, and heading or word list cues without a number
94//! (`headings for`, `a Summary heading`, `these words:`) that no recognizer consumed is
95//! UNCERTAIN. A bare count ("Keep it to 10 lines", "three sections") is therefore
96//! uncertain, never silent. Numbers without such a noun ("Fix the 2 typos") are ignored.
97//!
98//! Rules that keep it conservative:
99//! - the counted noun must END its clause: closing punctuation, end of goal, a
100//! joiner (`and or but so then because that which covering`) or one of
101//! `long with total overall titled named called about on including
102//! containing`, or `in total`. "3 lines of context", "5 items per category",
103//! "at least 4 questions in the survey" qualify the count and are UNCERTAIN.
104//! - a negator (`not no never without avoid` and contractions) up to 4 words
105//! before, in the same clause, makes the span UNCERTAIN (never inverted).
106//! - emphasis or quotes around the wording (`**at least 20 lines**`) are not
107//! recognized and the span is UNCERTAIN.
108//! - a bound word with a number and a noun that is not supported (`at most 5
109//! items`, `at most 3 paragraphs`, `exactly 20 lines`, `about 30 lines`,
110//! `between 10 and 20 items`, `35-line` with no verb before it) is UNCERTAIN.
111//! - a title list whose parsed length differs from a declared count ("6
112//! sections titled A, B, C") is UNCERTAIN; so is a list item that is not a
113//! short noun phrase.
114//! - the title or topic list is the text after the key word up to the end of
115//! the sentence (or `, each|with|which|that|...`, or a count bound); a
116//! trailing `and` splits the LAST comma item (`Who to ask and Glossary`),
117//! so a title that itself contains `and` is only safe inside the list.
118
119use crate::requirements::{content_words, topic_forms, word_keys, ItemKind, Requirement};
120
121/// What a goal says: recognized requirements and the spans it could not read.
122#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct Extraction {
124 pub requirements: Vec<Requirement>,
125 /// Goal text that looks like an explicit measurable requirement but could
126 /// not be interpreted reliably. Non-empty = the task must be refused.
127 pub uncertain: Vec<String>,
128}
129
130impl Extraction {
131 /// True when a requirement is measured against the prior file
132 /// ([`Requirement::AddedLines`]) and so needs [`Extraction::resolved`].
133 pub fn needs_prior(&self) -> bool {
134 self.requirements
135 .iter()
136 .any(|r| matches!(r, Requirement::AddedLines { .. }))
137 }
138
139 /// The same extraction with every added-line requirement bound to the
140 /// content of the file the proposal replaces (`""` for a new file).
141 pub fn resolved(mut self, prior: &str) -> Self {
142 for r in &mut self.requirements {
143 if let Requirement::AddedLines { prior: p, .. } = r {
144 *p = Some(prior.to_string());
145 }
146 }
147 self
148 }
149
150 /// The refusal reason when any span is uncertain.
151 pub fn refusal(&self) -> Option<String> {
152 (!self.uncertain.is_empty()).then(|| {
153 let spans: Vec<String> = self.uncertain.iter().map(|s| format!("\"{s}\"")).collect();
154 format!(
155 "uncertain requirement: the goal states a measurable requirement this runtime could not interpret reliably, so nothing was proposed: {}",
156 spans.join("; ")
157 )
158 })
159 }
160}
161
162/// Only the recognized requirements (see [`analyze`] for the uncertain spans).
163pub fn extract(goal: &str) -> Vec<Requirement> {
164 analyze(goal).requirements
165}
166
167struct Tok {
168 /// Lowercase with its punctuation.
169 raw: String,
170 /// `raw` without surrounding clause punctuation.
171 word: String,
172 /// `word` without emphasis and quote marks too.
173 norm: String,
174 start: usize,
175 end: usize,
176}
177
178fn clean(w: &str) -> &str {
179 w.trim_matches(|c: char| matches!(c, ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')'))
180}
181
182fn plain(w: &str) -> &str {
183 w.trim_matches(|c: char| {
184 matches!(
185 c,
186 ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')' | '*' | '_' | '"' | '\'' | '`'
187 )
188 })
189}
190
191fn tokenize(goal: &str) -> Vec<Tok> {
192 let mut out = Vec::new();
193 let mut start: Option<usize> = None;
194 let push = |out: &mut Vec<Tok>, s: usize, e: usize| {
195 let raw = goal[s..e].to_ascii_lowercase();
196 out.push(Tok {
197 word: clean(&raw).to_string(),
198 norm: plain(&raw).to_string(),
199 raw,
200 start: s,
201 end: e,
202 });
203 };
204 for (i, c) in goal.char_indices() {
205 if c.is_whitespace() {
206 if let Some(s) = start.take() {
207 push(&mut out, s, i);
208 }
209 } else if start.is_none() {
210 start = Some(i);
211 }
212 }
213 if let Some(s) = start {
214 push(&mut out, s, goal.len());
215 }
216 out
217}
218
219/// A word that ends its clause: it carries closing punctuation.
220fn ends_clause(raw: &str) -> bool {
221 raw.ends_with([',', '.', ';', ':', '!', '?', ')'])
222}
223
224/// The token ends a sentence: `.`, `!` or `?`, possibly before closing quotes
225/// or a bracket (`"Costs".` and `"Costs."` both end one).
226fn ends_sentence(raw: &str) -> bool {
227 raw.trim_end_matches(['"', '\'', '\u{201d}', '\u{2019}', ')'])
228 .ends_with(['.', '!', '?'])
229}
230
231/// The token range of the sentence holding token `i`.
232fn sentence_of(toks: &[Tok], i: usize) -> std::ops::Range<usize> {
233 let mut lo = i;
234 while lo > 0 && !ends_sentence(&toks[lo - 1].raw) {
235 lo -= 1;
236 }
237 let mut hi = i;
238 while hi + 1 < toks.len() && !ends_sentence(&toks[hi].raw) {
239 hi += 1;
240 }
241 lo..hi + 1
242}
243
244/// Nouns that name a part of the document, not the whole of it: a range or a
245/// bound in the same sentence may be about that part (sc#343 review).
246const PART_NOUNS: [&str; 22] = [
247 "paragraph",
248 "paragraphs",
249 "stanza",
250 "stanzas",
251 "verse",
252 "verses",
253 "bullet",
254 "bullets",
255 "entry",
256 "entries",
257 "item",
258 "items",
259 "sentence",
260 "sentences",
261 "gap",
262 "gaps",
263 "space",
264 "distance",
265 "row",
266 "rows",
267 "column",
268 "columns",
269];
270
271/// Words allowed right after the counted noun or the quoted phrase: they
272/// join a new clause instead of qualifying the count.
273const CLAUSE_JOINERS: [&str; 9] = [
274 "and", "or", "but", "so", "then", "because", "that", "which", "covering",
275];
276
277/// Other words that may follow the counted noun without changing its meaning.
278const NOUN_FOLLOWERS: [&str; 11] = [
279 "please", "thanks", "long", "with", "total", "overall", "titled", "named", "called", "about",
280 "on",
281];
282const NOUN_FOLLOWERS_2: [&str; 2] = ["including", "containing"];
283
284/// Words that turn a requirement into its opposite or into something else.
285const NEGATORS: [&str; 20] = [
286 "not",
287 "no",
288 "never",
289 "without",
290 "avoid",
291 "dont",
292 "don't",
293 "doesnt",
294 "doesn't",
295 "cant",
296 "can't",
297 "cannot",
298 "wont",
299 "won't",
300 "shouldnt",
301 "shouldn't",
302 "mustnt",
303 "mustn't",
304 "isnt",
305 "isn't",
306];
307
308/// True when one of the (at most 4) words before position `at` in the same
309/// clause is a negator. `raw` are the whitespace-split lowercase words.
310fn negated_before(toks: &[Tok], at: usize) -> bool {
311 for i in (at.saturating_sub(4)..at).rev() {
312 if ends_clause(&toks[i].raw) {
313 return false;
314 }
315 if NEGATORS.contains(&toks[i].word.as_str()) {
316 return true;
317 }
318 }
319 false
320}
321
322#[derive(Clone, Copy, PartialEq, Eq, Debug)]
323enum Dir {
324 Min,
325 Max,
326}
327
328/// (cue words, direction, adjustment: +1 strict min, -1 strict max).
329const CUES: [(&[&str], Dir, i64); 22] = [
330 (&["no", "longer", "than"], Dir::Max, 0),
331 (&["no", "shorter", "than"], Dir::Min, 0),
332 (&["no", "fewer", "than"], Dir::Min, 0),
333 (&["no", "less", "than"], Dir::Min, 0),
334 (&["not", "fewer", "than"], Dir::Min, 0),
335 (&["not", "less", "than"], Dir::Min, 0),
336 (&["no", "more", "than"], Dir::Max, 0),
337 (&["not", "more", "than"], Dir::Max, 0),
338 (&["a", "minimum", "of"], Dir::Min, 0),
339 (&["a", "maximum", "of"], Dir::Max, 0),
340 (&["minimum", "of"], Dir::Min, 0),
341 (&["maximum", "of"], Dir::Max, 0),
342 (&["at", "least"], Dir::Min, 0),
343 (&["at", "most"], Dir::Max, 0),
344 (&["more", "than"], Dir::Min, 1),
345 (&["fewer", "than"], Dir::Max, -1),
346 (&["less", "than"], Dir::Max, -1),
347 (&["up", "to"], Dir::Max, 0),
348 (&["minimum"], Dir::Min, 0),
349 (&["maximum"], Dir::Max, 0),
350 (&["min"], Dir::Min, 0),
351 (&["max"], Dir::Max, 0),
352];
353
354/// Cue words that state a bound or a size this module does not interpret.
355const VAGUE: [&str; 11] = [
356 "exactly",
357 "exact",
358 "about",
359 "around",
360 "approximately",
361 "roughly",
362 "nearly",
363 "between",
364 "over",
365 "under",
366 "below",
367];
368
369const NOUNS: [&str; 46] = [
370 "topic",
371 "topics",
372 "block",
373 "blocks",
374 "table",
375 "tables",
376 "column",
377 "columns",
378 "line",
379 "lines",
380 "word",
381 "words",
382 "item",
383 "items",
384 "step",
385 "steps",
386 "section",
387 "sections",
388 "heading",
389 "headings",
390 "question",
391 "questions",
392 "sentence",
393 "sentences",
394 "paragraph",
395 "paragraphs",
396 "bullet",
397 "bullets",
398 "point",
399 "points",
400 "entry",
401 "entries",
402 "row",
403 "rows",
404 "example",
405 "examples",
406 "page",
407 "pages",
408 "chapter",
409 "chapters",
410 "character",
411 "characters",
412 "command",
413 "commands",
414 "snippet",
415 "snippets",
416];
417
418/// Verbs that introduce a bare line count (`true` = exactly N added lines).
419fn line_verb(w: &str) -> Option<bool> {
420 match w {
421 "add" | "append" | "insert" | "with" => Some(true),
422 "write" | "put" | "create" | "draft" | "compose" | "produce" | "generate" => Some(false),
423 // "a file containing just one line" (sc#336)
424 "containing" => Some(true),
425 _ => None,
426 }
427}
428
429/// Words that may follow "N lines" without qualifying the count.
430const LINE_TAILS: [&str; 22] = [
431 "to",
432 "in",
433 "into",
434 "at",
435 "for",
436 "saying",
437 "describing",
438 "giving",
439 "listing",
440 "explaining",
441 "stating",
442 "that",
443 "which",
444 "under",
445 "after",
446 "before",
447 "below",
448 "above",
449 "telling",
450 "naming",
451 "mentioning",
452 "summarizing",
453];
454
455const CODE_NOUNS: [&str; 6] = [
456 "example", "examples", "block", "blocks", "snippet", "snippets",
457];
458const CODE_ADJ: [&str; 13] = [
459 "separate",
460 "fenced",
461 "code",
462 "shell",
463 "bash",
464 "distinct",
465 "different",
466 "small",
467 "short",
468 "runnable",
469 "sample",
470 "markdown",
471 "command-line",
472];
473const CODE_VERBS: [&str; 12] = [
474 "include", "includes", "add", "put", "provide", "give", "show", "use", "with", "contain",
475 "contains", "have",
476];
477
478const SECTION_NOUNS: [&str; 8] = [
479 "sections", "section", "headings", "heading", "chapters", "chapter", "parts", "part",
480];
481
482#[derive(Debug, PartialEq, Eq)]
483enum Num {
484 Val(usize),
485 /// Looks like a number (starts with a digit) but is zero or unparseable.
486 Bad,
487 Not,
488}
489
490fn small(w: &str) -> Option<usize> {
491 const ONES: [&str; 20] = [
492 "one",
493 "two",
494 "three",
495 "four",
496 "five",
497 "six",
498 "seven",
499 "eight",
500 "nine",
501 "ten",
502 "eleven",
503 "twelve",
504 "thirteen",
505 "fourteen",
506 "fifteen",
507 "sixteen",
508 "seventeen",
509 "eighteen",
510 "nineteen",
511 "twenty",
512 ];
513 const TENS: [(&str, usize); 8] = [
514 ("thirty", 30),
515 ("forty", 40),
516 ("fifty", 50),
517 ("sixty", 60),
518 ("seventy", 70),
519 ("eighty", 80),
520 ("ninety", 90),
521 ("hundred", 100),
522 ];
523 if let Some(i) = ONES.iter().position(|x| *x == w) {
524 return Some(i + 1);
525 }
526 TENS.iter().find(|(x, _)| *x == w).map(|(_, v)| *v)
527}
528
529fn parse_num(w: &str) -> Num {
530 if w.is_empty() {
531 return Num::Not;
532 }
533 if w.chars().all(|c| c.is_ascii_digit()) {
534 return match w.parse::<usize>() {
535 Ok(n) if n > 0 => Num::Val(n),
536 _ => Num::Bad,
537 };
538 }
539 if let Some(n) = small(w) {
540 return Num::Val(n);
541 }
542 if let Some((t, o)) = w.split_once('-') {
543 if let (Some(t), Some(o)) = (small(t), small(o)) {
544 if t >= 20 && t % 10 == 0 && t < 100 && o < 10 {
545 return Num::Val(t + o);
546 }
547 }
548 }
549 if w.starts_with(|c: char| c.is_ascii_digit())
550 || w.strip_prefix('-')
551 .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()))
552 {
553 return Num::Bad;
554 }
555 Num::Not
556}
557
558/// Match a cue at `s`; (length in tokens, direction, adjustment).
559fn match_cue(toks: &[Tok], s: usize, norm: bool) -> Option<(usize, Dir, i64)> {
560 let w = |i: usize| -> Option<&str> {
561 toks.get(i).map(|t| {
562 if norm {
563 t.norm.as_str()
564 } else {
565 t.word.as_str()
566 }
567 })
568 };
569 CUES.iter().find_map(|(words, dir, adj)| {
570 words
571 .iter()
572 .enumerate()
573 .all(|(k, x)| w(s + k) == Some(*x))
574 .then_some((words.len(), *dir, *adj))
575 })
576}
577
578fn qualifier_ok(toks: &[Tok], j: usize) -> bool {
579 if ends_clause(&toks[j].raw) {
580 return true;
581 }
582 match toks.get(j + 1) {
583 None => true,
584 Some(n) => {
585 let w = n.word.as_str();
586 let status = |s: &str| {
587 matches!(
588 s,
589 "needed" | "required" | "necessary" | "expected" | "enough" | "sufficient"
590 )
591 };
592 status(w)
593 || (matches!(w, "is" | "are")
594 && toks.get(j + 2).is_some_and(|t| status(t.word.as_str())))
595 || CLAUSE_JOINERS.contains(&w)
596 || NOUN_FOLLOWERS.contains(&w)
597 || NOUN_FOLLOWERS_2.contains(&w)
598 || (w == "in" && toks.get(j + 2).is_some_and(|t| clean(&t.raw) == "total"))
599 }
600 }
601}
602
603/// Words that make an unquoted "saying S" ambiguous: a pronoun or vague word
604/// (what is said is not named), a joiner (a second clause follows), or a
605/// preposition or instruction verb (S is not a plain phrase).
606const SAID_AMBIGUOUS: &[&str] = &[
607 "it",
608 "them",
609 "this",
610 "that",
611 "these",
612 "those",
613 "something",
614 "anything",
615 "everything",
616 "whatever",
617 "one",
618 "some",
619 "and",
620 "or",
621 "but",
622 "so",
623 "then",
624 "because",
625 "which",
626 "also",
627 "while",
628 "when",
629 "if",
630 "to",
631 "in",
632 "into",
633 "at",
634 "on",
635 "for",
636 "about",
637 "with",
638 "using",
639 "like",
640 "save",
641 "write",
642 "add",
643 "make",
644 "create",
645 "put",
646 "the",
647];
648
649/// sc#349: the unquoted text after `saying|reading|that says|reads`, starting
650/// at token `q`, read as a required phrase: one to three plain words that run to
651/// the end of the sentence, optionally followed by one destination file
652/// (`hello to a.md`). Returns the text and the byte after it; None when it is
653/// wider or ambiguous (see `SAID_AMBIGUOUS`), so the caller marks it uncertain.
654fn unquoted_said(goal: &str, toks: &[Tok], q: usize) -> Option<(String, usize)> {
655 let mut last = (q..toks.len())
656 .find(|&k| ends_sentence(&toks[k].raw))
657 .unwrap_or(toks.len().checked_sub(1)?);
658 // "hello to a.md": a lone path-like word after to|in|into|at is the destination.
659 if last >= q + 2
660 && matches!(toks[last - 1].word.as_str(), "to" | "in" | "into" | "at")
661 && toks[last].word.contains(['.', '/'])
662 {
663 last -= 2;
664 }
665 if last < q || last >= q + 3 {
666 return None;
667 }
668 for (k, t) in toks.iter().enumerate().take(last + 1).skip(q) {
669 let w = plain(&t.raw);
670 if (k < last && t.raw.ends_with([',', '.', ';', ':', '!', '?', ')']))
671 || w.is_empty()
672 || !w
673 .chars()
674 .all(|c| c.is_alphanumeric() || matches!(c, '\'' | '-'))
675 || SAID_AMBIGUOUS.contains(&w)
676 {
677 return None;
678 }
679 }
680 let end = toks[last].end;
681 let text = goal[toks[q].start..end].trim_end_matches([',', '.', ';', ':', '!', '?']);
682 Some((text.to_string(), end))
683}
684
685/// sc#336 / sc#349: the "saying" clause of a line, `noun` being the token of
686/// `line|lines`: `that says|reads S`, `saying|reading S`, also after one
687/// destination file (`to a.md saying S`). None when there is no such clause;
688/// Ok((S, end byte)) when S is read (quoted whole, or a short plain unquoted
689/// phrase, see `unquoted_said`); Err(()) when S is there but cannot be read.
690fn said_clause(goal: &str, toks: &[Tok], noun: usize) -> Option<Result<(String, usize), ()>> {
691 let w = |k: usize| toks.get(k).map(|t| t.word.as_str());
692 let at = if matches!(w(noun + 1), Some("to" | "in" | "into" | "at"))
693 && w(noun + 2).is_some_and(|p| p.contains(['.', '/']))
694 {
695 noun + 3
696 } else {
697 noun + 1
698 };
699 let q = match (w(at), w(at + 1)) {
700 (Some("that"), Some("says" | "reads" | "say" | "read")) => at + 2,
701 (Some("saying" | "reading"), _) => at + 1,
702 _ => return None,
703 };
704 if toks.get(q).is_none() {
705 return Some(Err(()));
706 }
707 let said = if toks[q].raw.starts_with(['"', '\u{201C}']) {
708 quoted_at(goal, toks, q)
709 } else {
710 unquoted_said(goal, toks, q)
711 };
712 Some(said.ok_or(()))
713}
714
715/// Mark the tokens that start inside the byte range as consumed.
716fn mark_bytes(handled: &mut std::collections::BTreeSet<usize>, toks: &[Tok], lo: usize, hi: usize) {
717 for (i, t) in toks.iter().enumerate() {
718 if t.start >= lo && t.start < hi {
719 handled.insert(i);
720 }
721 }
722}
723
724/// True when the text holds a number next to a countable noun ("5 steps").
725fn has_count_and_noun(t: &str) -> bool {
726 let w: Vec<String> = t
727 .split_whitespace()
728 .map(|x| plain(&x.to_ascii_lowercase()).to_string())
729 .collect();
730 (0..w.len()).any(|i| {
731 matches!(parse_num(&w[i]), Num::Val(_))
732 && (i + 1..=i + 2).any(|j| w.get(j).is_some_and(|x| NOUNS.contains(&x.as_str())))
733 })
734}
735
736/// Text of the goal from token `from` to the end of its clause (at most 10 tokens).
737fn snippet(goal: &str, toks: &[Tok], from: usize, commas: bool) -> String {
738 let ends = |raw: &str| {
739 if commas {
740 ends_clause(raw)
741 } else {
742 raw.ends_with(['.', '!', '?', ';'])
743 }
744 };
745 let mut to = from;
746 while to + 1 < toks.len() && to < from + 9 && !ends(&toks[to].raw) {
747 to += 1;
748 }
749 goal[toks[from].start..toks[to].end]
750 .trim_end_matches([',', '.', ';', ':', '!', '?'])
751 .to_string()
752}
753
754/// Sentence-counting words after the noun: `in|per|for|within [every|each|a|the|any] section(s)`.
755fn per_section_after(toks: &[Tok], j: usize) -> Option<usize> {
756 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
757 if !matches!(w(j + 1), Some("in" | "per" | "for" | "within" | "under")) {
758 return None;
759 }
760 let mut k = j + 2;
761 if matches!(w(k), Some("every" | "each" | "a" | "the" | "any")) {
762 k += 1;
763 }
764 matches!(w(k), Some("section" | "sections" | "heading" | "headings")).then_some(k)
765}
766
767/// "In every section, write ... N sentences": every|each section earlier in the sentence.
768fn every_section_before(toks: &[Tok], s: usize) -> bool {
769 for m in (s.saturating_sub(10)..s).rev() {
770 if m >= 1
771 && matches!(toks[m - 1].word.as_str(), "every" | "each")
772 && matches!(toks[m].word.as_str(), "section" | "heading")
773 {
774 return true;
775 }
776 if ends_clause(&toks[m].raw)
777 && m + 1 != s
778 && !matches!(toks[m].word.as_str(), "section" | "heading")
779 {
780 return false;
781 }
782 }
783 false
784}
785
786/// The text after a key word up to the end of its clause.
787fn list_region(goal: &str, from: usize) -> &str {
788 let rest = &goal[from..];
789 let b = rest.as_bytes();
790 let mut end = rest.len();
791 for (i, c) in rest.char_indices() {
792 if matches!(c, '.' | '!' | '?' | ';' | '\n')
793 && (i + 1 >= b.len() || (b[i + 1] as char).is_whitespace())
794 {
795 end = i;
796 break;
797 }
798 }
799 let mut region = &rest[..end];
800 let low = region.to_ascii_lowercase();
801 let mut cut = region.len();
802 for m in [
803 ", each ",
804 ", with ",
805 ", which ",
806 ", that ",
807 ", where ",
808 ", but ",
809 ", so ",
810 ", because ",
811 ", then ",
812 ", and each ",
813 ", and write ",
814 ", and make ",
815 " at least ",
816 " at most ",
817 " no more than ",
818 " no fewer than ",
819 " a minimum of ",
820 " up to ",
821 ] {
822 if let Some(i) = low.find(m) {
823 cut = cut.min(i);
824 }
825 }
826 region = &region[..cut];
827 // A bound often follows as "... in|of|with|and at least N": drop the dangling joiner.
828 let t = region.trim_end();
829 for tail in [" in", " of", " with", " and", " or", " within"] {
830 if t.to_ascii_lowercase().ends_with(tail) {
831 return &t[..t.len() - tail.len()];
832 }
833 }
834 t
835}
836
837fn quoted_items(region: &str) -> Vec<String> {
838 let mut out = Vec::new();
839 let mut open: Option<usize> = None;
840 for (i, c) in region.char_indices() {
841 match (c, open) {
842 ('"' | '\u{201C}', None) => open = Some(i + c.len_utf8()),
843 ('"' | '\u{201D}', Some(s)) => {
844 let t = region[s..i].trim();
845 if !t.is_empty() {
846 out.push(t.to_string());
847 }
848 open = None;
849 }
850 _ => {}
851 }
852 }
853 out
854}
855
856/// "of plain text", "of prose", "of body text" after a word count: the index of
857/// the last token of that phrase.
858fn plain_text_after(toks: &[Tok], j: usize) -> Option<usize> {
859 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
860 if w(j + 1) != Some("of") {
861 return None;
862 }
863 let mut k = j + 2;
864 if matches!(w(k), Some("plain" | "body" | "running" | "normal")) {
865 k += 1;
866 }
867 matches!(w(k), Some("text" | "prose" | "writing" | "plain-text")).then_some(k)
868}
869
870/// The section a sentence names before token `s`: `Some(None)` for "the last
871/// (or final) section", `Some(Some(title))` for `section titled "Title"` (a
872/// quoted title, or up to four plain words), None when the sentence names no
873/// section.
874fn section_scope_before(goal: &str, toks: &[Tok], s: usize) -> Option<Option<String>> {
875 let mut m = s;
876 while m > 0 {
877 m -= 1;
878 if m + 1 < s && toks[m].raw.ends_with(['.', '!', '?']) {
879 return None;
880 }
881 let w = toks[m].word.as_str();
882 if matches!(w, "last" | "final")
883 && toks
884 .get(m + 1)
885 .is_some_and(|t| matches!(t.word.as_str(), "section" | "heading"))
886 {
887 return Some(None);
888 }
889 if matches!(w, "titled" | "named" | "called")
890 && m >= 1
891 && matches!(toks[m - 1].word.as_str(), "section" | "heading")
892 {
893 let rest = goal[toks[m].end..].trim_start();
894 if rest.starts_with(['"', '\u{201C}']) {
895 let (q, _) = leading_quoted_items(rest);
896 return q.first().map(|t| Some(t.clone()));
897 }
898 let title: Vec<&str> = toks[m + 1..s]
899 .iter()
900 .take_while(|t| {
901 !matches!(
902 t.word.as_str(),
903 "that"
904 | "which"
905 | "with"
906 | "who"
907 | "where"
908 | "holds"
909 | "has"
910 | "and"
911 | "contains"
912 | "having"
913 ) && !t.raw.ends_with([',', '.', ';', ':'])
914 })
915 .map(|t| t.raw.as_str())
916 .collect();
917 return (!title.is_empty() && title.len() <= 4).then(|| Some(title.join(" ")));
918 }
919 }
920 None
921}
922
923/// Words that may stand between the quoted line prefix and the count cue
924/// ("... starting with "- [ ]" and I want at least 12 of those items").
925const OF_LINE_JOINERS: [&str; 11] = [
926 "and", "then", "also", "so", "i", "we", "want", "need", "include", "add", "write",
927];
928
929/// "<bound> N of them|these|those [items|lines|entries]" (`j` is the `of`): the
930/// count reads only when the same sentence (a line break also ends one), just
931/// before the cue, defines the
932/// counted lines as `lines starting|beginning|starts|begins with "P"` (singular
933/// `line` only after `every` or `each`, as in "every item on its own line"),
934/// with exactly one quoted prefix and at most four joining words
935/// (`OF_LINE_JOINERS`) between the closing quote and the cue. A negator or a
936/// per-section word (`per section heading chapter part`) anywhere in the
937/// sentence before the cue rejects it. Returns the last token of the count and
938/// the prefix as quoted (leading blanks dropped, a trailing space kept).
939fn of_line_prefix(goal: &str, toks: &[Tok], s: usize, j: usize) -> Option<(usize, String)> {
940 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
941 if !matches!(w(j + 1), Some("them" | "these" | "those")) {
942 return None;
943 }
944 let mut end = j + 1;
945 if !ends_clause(&toks[end].raw)
946 && matches!(w(end + 1), Some("items" | "item" | "lines" | "entries"))
947 {
948 end += 1;
949 }
950 if !qualifier_ok(toks, end) {
951 return None;
952 }
953 // (index of `with`, index of `line(s)`), and the first token of the sentence.
954 let mut found: Option<(usize, usize)> = None;
955 let mut first = 0;
956 let mut m = s;
957 while m > 0 {
958 m -= 1;
959 // A sentence ends at closing punctuation or at a line break.
960 if toks[m].raw.ends_with(['.', '!', '?'])
961 || goal[toks[m].end..toks[m + 1].start].contains('\n')
962 {
963 first = m + 1;
964 break;
965 }
966 let x = w(m).unwrap_or("");
967 if NEGATORS.contains(&x)
968 || matches!(
969 x,
970 "per"
971 | "section"
972 | "sections"
973 | "heading"
974 | "headings"
975 | "chapter"
976 | "chapters"
977 | "part"
978 | "parts"
979 )
980 {
981 return None;
982 }
983 if x == "with"
984 && m >= 2
985 && matches!(
986 w(m - 1),
987 Some("starting" | "beginning" | "starts" | "begins" | "start" | "begin")
988 )
989 {
990 let mut l = m - 2;
991 if w(l) == Some("that") && l >= 1 {
992 l -= 1;
993 }
994 if matches!(w(l), Some("line" | "lines")) {
995 if found.is_some() {
996 return None;
997 }
998 found = Some((m, l));
999 }
1000 }
1001 }
1002 let (with, line) = found?;
1003 if w(line) == Some("line")
1004 && !toks[first..line]
1005 .iter()
1006 .any(|t| matches!(t.word.as_str(), "every" | "each"))
1007 {
1008 return None;
1009 }
1010 let rest = &goal[toks[with].end..];
1011 if leading_quoted_items(rest).0.len() != 1 {
1012 return None;
1013 }
1014 let t = rest.trim_start();
1015 let open = t.chars().next()?.len_utf8();
1016 let body = &t[open..];
1017 let close = body.find(['"', '\u{201D}'])?;
1018 let prefix = body[..close].trim_start();
1019 if prefix.trim().is_empty() {
1020 return None;
1021 }
1022 // Only joining words between the closing quote and the cue.
1023 let closer = body[close..].chars().next().map_or(1, char::len_utf8);
1024 let after = toks[with].end + (rest.len() - t.len()) + open + close + closer;
1025 let between: Vec<&Tok> = toks[..s].iter().filter(|t| t.start >= after).collect();
1026 if between.len() > 4
1027 || !between
1028 .iter()
1029 .all(|t| OF_LINE_JOINERS.contains(&t.word.as_str()))
1030 {
1031 return None;
1032 }
1033 Some((end, prefix.to_string()))
1034}
1035
1036/// The heading level an adjective names: `level-two`, `level-2`, `second-level`, `h2`.
1037fn level_adj(w: &str) -> Option<usize> {
1038 let lv = |v: usize| (1..=6).contains(&v).then_some(v);
1039 if let Some(r) = w.strip_prefix("level-") {
1040 return match parse_num(r) {
1041 Num::Val(v) => lv(v),
1042 _ => None,
1043 };
1044 }
1045 if let Some(r) = w.strip_suffix("-level") {
1046 return ["first", "second", "third", "fourth", "fifth", "sixth"]
1047 .iter()
1048 .position(|x| *x == r)
1049 .map(|p| p + 1);
1050 }
1051 let b = w.as_bytes();
1052 (b.len() == 2 && b[0] == b'h' && (b'1'..=b'6').contains(&b[1])).then(|| (b[1] - b'0') as usize)
1053}
1054
1055/// The consecutive quoted items a region STARTS with, separated only by
1056/// commas, `and` or `or`; the byte offset just after the last one is returned
1057/// too. Empty when the region does not start with a quote.
1058fn leading_quoted_items(region: &str) -> (Vec<String>, usize) {
1059 let mut out = Vec::new();
1060 let mut at = 0;
1061 loop {
1062 let rest = &region[at..];
1063 let t = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ',');
1064 let t_lc = t.to_ascii_lowercase();
1065 let skip = if !out.is_empty() {
1066 ["and ", "or "]
1067 .iter()
1068 .find(|p| t_lc.starts_with(**p))
1069 .map_or(0, |p| p.len())
1070 } else {
1071 0
1072 };
1073 let t2 = t[skip..].trim_start();
1074 let Some(open) = t2.chars().next().filter(|c| matches!(c, '"' | '\u{201C}')) else {
1075 break;
1076 };
1077 let body = &t2[open.len_utf8()..];
1078 let Some(close) = body.find(['"', '\u{201D}']) else {
1079 break;
1080 };
1081 let item = body[..close].trim();
1082 if !item.is_empty() {
1083 out.push(item.to_string());
1084 }
1085 let closer = body[close..].chars().next().map_or(1, char::len_utf8);
1086 at = region.len() - body.len() + close + closer;
1087 }
1088 (out, at)
1089}
1090
1091/// Comma separated items; the LAST comma item is also split at its last `and`/`or`.
1092fn split_list(region: &str) -> Vec<String> {
1093 let strip = |s: &str| -> String {
1094 let t = s.trim();
1095 let l = t.to_ascii_lowercase();
1096 for p in ["and ", "or "] {
1097 if l.starts_with(p) {
1098 return t[p.len()..].trim().to_string();
1099 }
1100 }
1101 t.to_string()
1102 };
1103 let mut segs: Vec<String> = region
1104 .split(',')
1105 .map(strip)
1106 .filter(|s| !s.is_empty())
1107 .collect();
1108 if let Some(last) = segs.pop() {
1109 let l = last.to_ascii_lowercase();
1110 let at = [" and ", " or "]
1111 .iter()
1112 .filter_map(|m| l.rfind(m).map(|i| (i, m.len())))
1113 .max_by_key(|x| x.0);
1114 match at {
1115 Some((i, n)) if !last[..i].trim().is_empty() && !last[i + n..].trim().is_empty() => {
1116 segs.push(last[..i].trim().to_string());
1117 segs.push(last[i + n..].trim().to_string());
1118 }
1119 _ => segs.push(last),
1120 }
1121 }
1122 segs
1123}
1124
1125/// The quoted text that token `q` opens and the byte after its closing
1126/// quote: `"Renew the card on Friday."` is `Renew the card on Friday` when the
1127/// quote closes the goal sentence (its final `.` `!` `?` is the goal's own).
1128fn quoted_at(goal: &str, toks: &[Tok], q: usize) -> Option<(String, usize)> {
1129 let start = toks.get(q)?.start;
1130 let open = goal[start..].chars().next()?;
1131 let close = match open {
1132 '"' => '"',
1133 '\u{201C}' => '\u{201D}',
1134 _ => return None,
1135 };
1136 let body_at = start + open.len_utf8();
1137 let len = goal[body_at..].find(close)?;
1138 let end = body_at + len + close.len_utf8();
1139 let body = goal[body_at..body_at + len].trim_end();
1140 let rest = &goal[end..];
1141 let next = rest.trim_start();
1142 // The goal sentence ends inside the quote: at the end of the goal, or
1143 // before a new capitalised sentence when the quoted text ends in . ! ?
1144 let closes_goal = next.is_empty()
1145 || body.ends_with(['.', '!', '?'])
1146 && rest.starts_with(char::is_whitespace)
1147 && next.starts_with(char::is_uppercase);
1148 // The goal sentence ends just after the quote: `"S".`
1149 let stop_after = rest.starts_with(['.', '!', '?'])
1150 && rest[1..].chars().next().is_none_or(char::is_whitespace);
1151 let text = if closes_goal {
1152 body.trim_end_matches(['.', '!', '?'])
1153 } else if stop_after {
1154 body
1155 } else {
1156 // anything else ("in bold", "and another line", a stray inner quote)
1157 // may change what the line holds
1158 return None;
1159 };
1160 let text = text.trim();
1161 (!text.is_empty()).then(|| (text.to_string(), end))
1162}
1163
1164/// A list region cut after the item that follows its closing "and" or "or":
1165/// "interest, deposit, withdraw and balance, and the file needs" is
1166/// "interest, deposit, withdraw and balance". None when that last item holds
1167/// another "and" or "or" ("labelling and storage and disposal").
1168fn closed_list(region: &str) -> Option<&str> {
1169 let low = region.to_ascii_lowercase();
1170 let Some(join) = [" and ", " or "].iter().filter_map(|j| low.find(j)).min() else {
1171 return Some(region);
1172 };
1173 let end = region[join..].find(',').map_or(region.len(), |c| join + c);
1174 let last = &low[join + 4..end];
1175 (!last.contains(" and ") && !last.contains(" or ")).then_some(&region[..end])
1176}
1177
1178/// `(position, forms)` for each "<form> or <form> for the first|second|...|
1179/// last [one|topic]" in a sentence that speaks of a word "form", for a list of
1180/// `len` topics.
1181fn positional_forms(goal: &str, len: usize) -> Vec<(usize, Vec<String>)> {
1182 const ORDINALS: [&str; 12] = [
1183 "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
1184 "tenth", "eleventh", "twelfth",
1185 ];
1186 let mut out = Vec::new();
1187 for sentence in goal.split_inclusive(['.', '!', '?']) {
1188 let low = sentence.to_ascii_lowercase();
1189 if !low
1190 .split(|c: char| !c.is_ascii_alphabetic())
1191 .any(|w| matches!(w, "form" | "forms"))
1192 {
1193 continue;
1194 }
1195 let Some(cue) = ["for example", "for instance", "such as", "e.g."]
1196 .iter()
1197 .filter_map(|c| low.find(c).map(|i| i + c.len()))
1198 .min()
1199 else {
1200 continue;
1201 };
1202 for seg in low[cue..].split([',', ';']) {
1203 let seg = seg.trim().trim_end_matches(['.', '!', '?']);
1204 let seg = seg.strip_prefix("and ").unwrap_or(seg);
1205 let Some((forms, pos)) = seg.split_once(" for the ") else {
1206 continue;
1207 };
1208 let ord = pos.split_whitespace().next().unwrap_or("");
1209 let at = match ORDINALS.iter().position(|o| *o == ord) {
1210 Some(i) if i < len => i,
1211 None if ord == "last" => len - 1,
1212 _ => continue,
1213 };
1214 let forms: Vec<String> = forms
1215 .split(" or ")
1216 .flat_map(|f| f.split(" and "))
1217 .map(|f| f.trim().to_string())
1218 .filter(|f| !f.is_empty() && f.split_whitespace().count() == 1)
1219 .collect();
1220 if !forms.is_empty() {
1221 out.push((at, forms));
1222 }
1223 }
1224 }
1225 out
1226}
1227
1228/// Words that may name the whole document as the place a word must appear:
1229/// "somewhere", "anywhere", "in it", "in the text|file|document|list". A part
1230/// that may be a section ("the summary", "the body", "the notes") is not one.
1231const PLACE_WORDS: [&str; 9] = [
1232 "somewhere",
1233 "anywhere",
1234 "in",
1235 "it",
1236 "the",
1237 "text",
1238 "file",
1239 "document",
1240 "list",
1241];
1242
1243/// Titles written with a period, so the name continues after it ("Dr. Smith").
1244const NAME_TITLES: [&str; 10] = [
1245 "dr", "mr", "mrs", "ms", "prof", "st", "jr", "sr", "mt", "rev",
1246];
1247
1248/// Words after ", and" that open a new instruction ("..., and write 5 lines").
1249const CLAUSE_VERBS: [&str; 13] = [
1250 "then", "write", "add", "be", "keep", "make", "save", "put", "please", "give", "end", "start",
1251 "finish",
1252];
1253
1254/// Words after ", and" that open a new clause when a verb soon follows ("...,
1255/// and the file needs at least 14 lines", "..., and it must be short").
1256const CLAUSE_SUBJECTS: [&str; 8] = ["the", "it", "its", "this", "that", "there", "i", "we"];
1257
1258/// Verbs that make a `CLAUSE_SUBJECTS` opener a clause rather than one more item.
1259const CLAUSE_AUX: [&str; 18] = [
1260 "must", "should", "needs", "need", "is", "are", "has", "have", "will", "can", "shall", "would",
1261 "want", "wants", "stays", "stay", "gets", "get",
1262];
1263
1264/// Words in the clause after ", and" that may add to the list or bind it.
1265const CLAUSE_MENTIONS: [&str; 19] = [
1266 "name", "names", "named", "mention", "mentions", "appear", "appears", "include", "includes",
1267 "contain", "contains", "use", "uses", "twice", "once", "thrice", "too", "also", "each",
1268];
1269
1270/// The text after a word or name list ends it cleanly: nothing, a sentence end
1271/// (not after a title such as "Dr", and not a next sentence that starts with
1272/// "and" or "or"), or ", and" opening a new instruction or clause. Anything
1273/// else after the list ("at least twice", ", but only in the summary", "; and
1274/// Tomas", ", and also Wen", ", and nothing else") may bind to it, and the
1275/// list is then uncertain (sc#345 review).
1276fn list_ends_cleanly(after: &str, last_item: &str) -> bool {
1277 let t = after.trim_start_matches([' ', '\t']);
1278 if t.is_empty() || t.starts_with(['\n', '\r']) {
1279 return true;
1280 }
1281 if t.starts_with(['.', '!', '?']) {
1282 let next = t[1..].split_whitespace().next().map(clean).unwrap_or("");
1283 return !(t.starts_with('.')
1284 && NAME_TITLES.contains(&last_item.to_ascii_lowercase().as_str()))
1285 && !matches!(next.to_ascii_lowercase().as_str(), "and" | "or");
1286 }
1287 let t = t.strip_prefix(',').unwrap_or(t);
1288 // The new clause runs to the end of its sentence; it must not carry a name
1289 // or word requirement of its own ("..., and I want Wen too", "..., and add Z").
1290 let end = t
1291 .char_indices()
1292 .find(|&(i, c)| {
1293 c == '\n'
1294 || (matches!(c, '.' | '!' | '?')
1295 && t[i + 1..].chars().next().is_none_or(char::is_whitespace))
1296 })
1297 .map_or(t.len(), |(i, _)| i);
1298 let raw: Vec<&str> = t[..end].split_whitespace().collect();
1299 let names_more = raw.iter().skip(2).any(|x| {
1300 let x = plain(x);
1301 let low = x.to_ascii_lowercase();
1302 (x.starts_with(|c: char| c.is_uppercase()) && x != "I")
1303 || CLAUSE_MENTIONS.contains(&low.as_str())
1304 });
1305 if names_more {
1306 return false;
1307 }
1308 let ws: Vec<String> = raw
1309 .iter()
1310 .take(7)
1311 .map(|x| clean(x).to_ascii_lowercase())
1312 .collect();
1313 if ws.first().map(String::as_str) != Some("and") {
1314 return false;
1315 }
1316 match ws.get(1).map(String::as_str) {
1317 Some(x) if CLAUSE_VERBS.contains(&x) => true,
1318 Some(x) if CLAUSE_SUBJECTS.contains(&x) => {
1319 ws[2..].iter().any(|x| CLAUSE_AUX.contains(&x.as_str()))
1320 }
1321 _ => false,
1322 }
1323}
1324
1325/// The list offers a choice ("Priya or Tomas"): a required-words list is all of them.
1326fn is_choice(list: &str) -> bool {
1327 // Only the words outside quotes: a quoted phrase may itself hold "or".
1328 let mut outside = String::new();
1329 let mut quoted = false;
1330 for c in list.chars() {
1331 match c {
1332 '"' => quoted = !quoted,
1333 '\u{201C}' => quoted = true,
1334 '\u{201D}' => quoted = false,
1335 _ if !quoted => outside.push(c),
1336 _ => {}
1337 }
1338 }
1339 outside
1340 .split_whitespace()
1341 .any(|x| matches!(clean(x).to_ascii_lowercase().as_str(), "or" | "either"))
1342}
1343
1344/// "somewhere in the list", "anywhere in it": a place that is the whole document.
1345fn whole_document_place(t: &str) -> bool {
1346 t.split_whitespace()
1347 .all(|x| PLACE_WORDS.contains(&plain(&x.to_ascii_lowercase())))
1348}
1349
1350/// The word list and the last token of `the words X and Y [both|all] appear|
1351/// appears|occur|occurs|show up|shows up|are used|is used|are included|are
1352/// present [somewhere in it]` (`k` is `the`, `q` the noun). None when anything
1353/// else follows, a negator sits in the clause, or an item is not one word.
1354fn words_must_appear(goal: &str, toks: &[Tok], k: usize, q: usize) -> Option<(Vec<String>, usize)> {
1355 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
1356 if negated_before(toks, k - 1) {
1357 return None;
1358 }
1359 // The verb, in the same clause as the noun.
1360 let mut v = q + 1;
1361 loop {
1362 let x = w(v)?;
1363 if NEGATORS.contains(&x) {
1364 return None;
1365 }
1366 if matches!(
1367 x,
1368 "appear" | "appears" | "occur" | "occurs" | "show" | "shows" | "are" | "is"
1369 ) {
1370 break;
1371 }
1372 // Commas separate the list items; a sentence or clause mark ends the search.
1373 if toks[v].raw.ends_with(['.', ';', ':', '!', '?', ')']) {
1374 return None;
1375 }
1376 v += 1;
1377 }
1378 let mut items_end = v;
1379 if matches!(w(v - 1), Some("both" | "all" | "each")) {
1380 items_end = v - 1;
1381 }
1382 if items_end <= q + 1 {
1383 return None;
1384 }
1385 let items: Vec<String> = split_list(&goal[toks[q].end..toks[items_end].start])
1386 .iter()
1387 .map(|t| trim_title(t))
1388 .collect();
1389 if items.is_empty()
1390 || items.len() > 20
1391 || !items
1392 .iter()
1393 .all(|t| !t.is_empty() && t.split_whitespace().count() == 1)
1394 {
1395 return None;
1396 }
1397 let mut last = v;
1398 match w(v)? {
1399 "show" | "shows" => {
1400 if w(v + 1) != Some("up") {
1401 return None;
1402 }
1403 last = v + 1;
1404 }
1405 "are" | "is" => {
1406 if !matches!(w(v + 1), Some("used" | "included" | "present")) {
1407 return None;
1408 }
1409 last = v + 1;
1410 }
1411 _ => {}
1412 }
1413 // The rest of the clause names the whole document, or nothing.
1414 while !ends_clause(&toks[last].raw) {
1415 match w(last + 1) {
1416 None => break,
1417 Some(x) if CLAUSE_JOINERS.contains(&x) => break,
1418 Some(x) if PLACE_WORDS.contains(&x) => last += 1,
1419 Some(_) => return None,
1420 }
1421 }
1422 // The clause must end there, not carry a count or a narrowing on.
1423 let raw = &toks[last].raw;
1424 let punct = raw.len()
1425 - raw
1426 .trim_end_matches([',', '.', ';', ':', '!', '?', ')'])
1427 .len();
1428 if !list_ends_cleanly(&goal[toks[last].end - punct..], "")
1429 || is_choice(&goal[toks[q].end..toks[items_end].start])
1430 {
1431 return None;
1432 }
1433 Some((items, last))
1434}
1435
1436fn trim_title(t: &str) -> String {
1437 t.trim()
1438 .trim_matches(|c: char| matches!(c, '"' | '\'' | '\u{201C}' | '\u{201D}' | '*' | '_' | '`'))
1439 .trim()
1440 .to_string()
1441}
1442
1443/// The requirements stated in `goal` and the spans that could not be read.
1444pub fn analyze(goal: &str) -> Extraction {
1445 let toks = tokenize(goal);
1446 let n = toks.len();
1447 let mut handled: std::collections::BTreeSet<usize> = Default::default();
1448 let mut unsure: Vec<(usize, String)> = Vec::new();
1449 let mut counts: Vec<Requirement> = Vec::new();
1450 let mut headings: Vec<String> = Vec::new();
1451 let mut level_headings: Vec<(usize, Vec<String>)> = Vec::new();
1452 let mut topics: Vec<String> = Vec::new();
1453 let mut phrases: Vec<String> = Vec::new();
1454 let mut words: Vec<String> = Vec::new();
1455 let add = |v: &mut Vec<Requirement>, r: Requirement| {
1456 if !v.contains(&r) {
1457 v.push(r);
1458 }
1459 };
1460 let bad = |unsure: &mut Vec<(usize, String)>, at: usize, commas: bool| {
1461 unsure.push((at, snippet(goal, &toks, at, commas)));
1462 };
1463
1464 // ---- counts: cue N noun, and N or more|fewer noun, N+ noun ----
1465 let count_req = |dir: Dir, noun: &str, v: usize| -> Option<Requirement> {
1466 Some(match (dir, noun) {
1467 (Dir::Min, "lines" | "line") => Requirement::MinLines(v),
1468 (Dir::Max, "lines" | "line") => Requirement::MaxLines(v),
1469 (Dir::Min, "words" | "word") => Requirement::MinWords(v),
1470 (Dir::Max, "words" | "word") => Requirement::MaxWords(v),
1471 (Dir::Min, "items" | "item") => Requirement::MinItems(ItemKind::Items, v),
1472 (Dir::Min, "steps" | "step") => Requirement::MinItems(ItemKind::Steps, v),
1473 (Dir::Min, "sections" | "section" | "headings" | "heading") => {
1474 Requirement::MinItems(ItemKind::Sections, v)
1475 }
1476 (Dir::Min, "questions" | "question") => Requirement::MinItems(ItemKind::Questions, v),
1477 (Dir::Min, "paragraphs" | "paragraph") => Requirement::MinParagraphs(v),
1478 _ => return None,
1479 })
1480 };
1481 for s in 0..n {
1482 // "between N and M lines|words": inclusive, N <= M (sc#331).
1483 if toks[s].word == "between" {
1484 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
1485 if let (Some(Num::Val(lo)), Some("and"), Some(Num::Val(hi)), Some(noun)) = (
1486 w(s + 1).map(parse_num),
1487 w(s + 2),
1488 w(s + 3).map(parse_num),
1489 w(s + 4),
1490 ) {
1491 let pair = match noun {
1492 "lines" | "line" => {
1493 Some((Requirement::MinLines(lo), Requirement::MaxLines(hi)))
1494 }
1495 "words" | "word" => {
1496 Some((Requirement::MinWords(lo), Requirement::MaxWords(hi)))
1497 }
1498 _ => None,
1499 };
1500 // Not about a part of the document ("each paragraph between ...",
1501 // "the gap between ..."), and not approximate ("... lines or so",
1502 // "roughly", "approximately", "give or take", "-ish").
1503 // Anywhere earlier in the sentence: "every single long paragraph
1504 // stays between ...", "its stanzas are between ...".
1505 let part = s >= 1 && NOUNS.contains(&toks[s - 1].word.as_str())
1506 || toks[sentence_of(&toks, s).start..s].iter().any(|t| {
1507 let t = t.word.as_str();
1508 matches!(t, "each" | "every" | "per")
1509 || PART_NOUNS.contains(&t)
1510 || SECTION_NOUNS.contains(&t)
1511 });
1512 let o = if w(s + 5) == Some("long") {
1513 s + 6
1514 } else {
1515 s + 5
1516 };
1517 let or_so = (w(o) == Some("or") && w(o + 1) == Some("so"))
1518 || matches!(w(o), Some("roughly" | "approximately" | "ish"))
1519 || (w(o) == Some("give") && w(o + 1) == Some("or") && w(o + 2) == Some("take"));
1520 if let Some((a, b)) = pair {
1521 if lo <= hi
1522 && !part
1523 && !or_so
1524 && !negated_before(&toks, s)
1525 && qualifier_ok(&toks, s + 4)
1526 {
1527 add(&mut counts, a);
1528 add(&mut counts, b);
1529 handled.extend(s..=s + 4);
1530 }
1531 }
1532 }
1533 continue;
1534 }
1535 // "under|below N words|lines" = fewer than N; "within N words|lines" = at
1536 // most N (sc#383). Only words and lines: "under three sections" names a
1537 // structure, "under 80 characters" a measure nothing checks; both stay with
1538 // the recognizers above or UNCERTAIN.
1539 let near_max = match toks[s].word.as_str() {
1540 "under" | "below" => Some(-1i64),
1541 "within" => Some(0),
1542 _ => None,
1543 };
1544 if let (Some(adj), Some(Num::Val(v)), Some(noun)) = (
1545 near_max,
1546 toks.get(s + 1).map(|t| parse_num(&t.word)),
1547 toks.get(s + 2).map(|t| t.word.as_str()),
1548 ) {
1549 let v = v as i64 + adj;
1550 if matches!(noun, "words" | "word" | "lines" | "line")
1551 && v >= 1
1552 && !negated_before(&toks, s)
1553 && qualifier_ok(&toks, s + 2)
1554 {
1555 if let Some(r) = count_req(Dir::Max, noun, v as usize) {
1556 add(&mut counts, r);
1557 handled.extend(s..=s + 2);
1558 continue;
1559 }
1560 }
1561 }
1562 // "N <noun> or more|fewer|less" and "N <noun> minimum|maximum".
1563 if let (Num::Val(v), Some(noun)) = (
1564 parse_num(&toks[s].word),
1565 toks.get(s + 1).map(|t| t.word.as_str()),
1566 ) {
1567 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
1568 let post = match (w(s + 2), w(s + 3)) {
1569 (Some("or"), Some("more")) => Some((Dir::Min, s + 3)),
1570 (Some("or"), Some("fewer" | "less")) => Some((Dir::Max, s + 3)),
1571 (Some("minimum" | "min"), _) => Some((Dir::Min, s + 2)),
1572 (Some("maximum" | "max"), _) => Some((Dir::Max, s + 2)),
1573 _ => None,
1574 };
1575 if let Some((dir, end)) = post {
1576 if NOUNS.contains(&noun) && !negated_before(&toks, s) && qualifier_ok(&toks, end) {
1577 if let Some(r) = count_req(dir, noun, v) {
1578 add(&mut counts, r);
1579 handled.extend(s..=end);
1580 continue;
1581 }
1582 }
1583 }
1584 }
1585 // "N or more|fewer|less <noun>" and "N+ <noun>": the number leads.
1586 let lead = match parse_num(toks[s].word.trim_end_matches('+')) {
1587 Num::Val(v) if toks[s].word.ends_with('+') => Some((v, Dir::Min, s + 1)),
1588 Num::Val(v)
1589 if toks.get(s + 1).is_some_and(|t| t.word == "or")
1590 && toks
1591 .get(s + 2)
1592 .is_some_and(|t| matches!(t.word.as_str(), "more" | "fewer" | "less")) =>
1593 {
1594 let d = if toks[s + 2].word == "more" {
1595 Dir::Min
1596 } else {
1597 Dir::Max
1598 };
1599 Some((v, d, s + 3))
1600 }
1601 _ => None,
1602 };
1603 if let Some((v, dir, j)) = lead {
1604 if let Some(noun) = toks.get(j).map(|t| t.word.as_str()) {
1605 if NOUNS.contains(&noun) && !negated_before(&toks, s) && qualifier_ok(&toks, j) {
1606 if let Some(r) = count_req(dir, noun, v) {
1607 add(&mut counts, r);
1608 handled.extend(s..=j);
1609 }
1610 }
1611 }
1612 continue;
1613 }
1614 let Some((len, dir, adj)) = match_cue(&toks, s, false) else {
1615 continue;
1616 };
1617 let i = s + len;
1618 let Some(numtok) = toks.get(i) else { continue };
1619 let Num::Val(v) = parse_num(&numtok.word) else {
1620 continue;
1621 };
1622 // "at least 20 lines and no more than 40": the second noun is elided
1623 // (#344). Read it with the earlier noun, or report it UNCERTAIN; never drop it.
1624 let next_is_noun = toks
1625 .get(i + 1)
1626 .is_some_and(|t| NOUNS.contains(&t.word.as_str()));
1627 if !next_is_noun && qualifier_ok(&toks, i) && !negated_before(&toks, s) {
1628 let sent = sentence_of(&toks, s);
1629 let joined =
1630 s > sent.start && matches!(toks[s - 1].word.as_str(), "and" | "or" | "but");
1631 // the noun of the count that ends right before the joiner
1632 let antecedent = if joined {
1633 (sent.start..s - 1).rev().find_map(|p| {
1634 let (l, _, _) = match_cue(&toks, p, false)?;
1635 let Num::Val(_) = parse_num(&toks.get(p + l)?.word) else {
1636 return None;
1637 };
1638 let mut j = p + l + 1;
1639 if toks.get(j).is_some_and(|t| {
1640 matches!(t.word.as_str(), "non-empty" | "nonempty" | "non-blank")
1641 }) {
1642 j += 1;
1643 }
1644 let noun = toks.get(j)?.word.as_str();
1645 // the noun sits right before the joiner (an optional "long" between)
1646 let gap_ok = j + 1 == s - 1 || (j + 2 == s - 1 && toks[j + 1].word == "long");
1647 (NOUNS.contains(&noun) && handled.contains(&p) && gap_ok).then_some(noun)
1648 })
1649 } else {
1650 None
1651 };
1652 let v = v as i64 + adj;
1653 match antecedent.and_then(|noun| count_req(dir, noun, v.max(1) as usize)) {
1654 Some(r) if v >= 1 => {
1655 add(&mut counts, r);
1656 handled.extend(s..=i);
1657 }
1658 _ => {
1659 bad(&mut unsure, s, true);
1660 handled.extend(s..=i);
1661 }
1662 }
1663 continue;
1664 }
1665 let mut j = i + 1;
1666 // "non-empty lines": line counts are over non-empty lines already (sc#331).
1667 if toks
1668 .get(j)
1669 .is_some_and(|t| matches!(t.word.as_str(), "non-empty" | "nonempty" | "non-blank"))
1670 && toks
1671 .get(j + 1)
1672 .is_some_and(|t| matches!(t.word.as_str(), "lines" | "line"))
1673 {
1674 j += 1;
1675 }
1676 let Some(noun) = toks.get(j).map(|t| t.word.as_str()) else {
1677 continue;
1678 };
1679 // "at least twelve of them", the lines named earlier in the sentence (sc#334).
1680 if noun == "of" {
1681 if let Some((end, prefix)) = of_line_prefix(goal, &toks, s, j) {
1682 let v = v as i64 + adj;
1683 if dir == Dir::Min && v >= 1 && !negated_before(&toks, s) {
1684 add(
1685 &mut counts,
1686 Requirement::MinPrefixedLines {
1687 prefix,
1688 n: v as usize,
1689 },
1690 );
1691 handled.extend(s..=end);
1692 }
1693 }
1694 continue;
1695 }
1696 if !NOUNS.contains(&noun) || negated_before(&toks, s) {
1697 continue;
1698 }
1699 if matches!(noun, "sentences" | "sentence") {
1700 let after = per_section_after(&toks, j);
1701 if dir == Dir::Min && (after.is_some() || every_section_before(&toks, s)) {
1702 let v = (v as i64 + adj) as usize;
1703 add(&mut counts, Requirement::MinSentencesPerSection(v));
1704 handled.extend(s..=after.unwrap_or(j));
1705 }
1706 continue;
1707 }
1708 if matches!(noun, "words" | "word") {
1709 if let Some(end) = plain_text_after(&toks, j) {
1710 // "N words of plain text" is a count over a scope the goal must name.
1711 if dir == Dir::Min {
1712 if let Some(scope) = section_scope_before(goal, &toks, s) {
1713 let v = v as i64 + adj;
1714 if v >= 1 {
1715 add(
1716 &mut counts,
1717 Requirement::SectionMinWords {
1718 title: scope,
1719 n: v as usize,
1720 },
1721 );
1722 handled.extend(s..=end);
1723 }
1724 }
1725 }
1726 continue;
1727 }
1728 }
1729 if !qualifier_ok(&toks, j) {
1730 continue;
1731 }
1732 let v = v as i64 + adj;
1733 if v < 1 {
1734 continue;
1735 }
1736 if let Some(r) = count_req(dir, noun, v as usize) {
1737 add(&mut counts, r);
1738 handled.extend(s..=j);
1739 }
1740 }
1741
1742 // ---- bare line counts: "Add 2 lines", "Write 20 lines about X", "a two-line poem" ----
1743 // The verb decides the reading: add|append|insert|with N lines = exactly N
1744 // lines added; write|put|create|draft|... N lines = at least N lines added;
1745 // an adjective "N-line" after a verb = exactly N lines. Measured against the
1746 // prior file (a new file has none), see `Requirement::AddedLines`.
1747 for s in 0..n {
1748 let Some(mut exact) = line_verb(&toks[s].word) else {
1749 continue;
1750 };
1751 if handled.contains(&s) || negated_before(&toks, s) {
1752 continue;
1753 }
1754 let mut i = s + 1;
1755 while toks.get(i).is_some_and(|t| {
1756 matches!(
1757 t.word.as_str(),
1758 "a" | "an" | "the" | "just" | "only" | "exactly"
1759 )
1760 }) {
1761 if toks[i].word == "exactly" {
1762 exact = true;
1763 }
1764 i += 1;
1765 }
1766 let Some(t) = toks.get(i) else { continue };
1767 if handled.contains(&i) {
1768 continue;
1769 }
1770 // "two-line", "1-line" (an adjective: the document is that long)
1771 if let Some((a, b)) = t.word.split_once('-') {
1772 if let (Num::Val(v), "line" | "lines") = (parse_num(a), b) {
1773 add(
1774 &mut counts,
1775 Requirement::AddedLines {
1776 n: v,
1777 exact: true,
1778 prior: None,
1779 },
1780 );
1781 handled.extend(s..=i);
1782 }
1783 continue;
1784 }
1785 let num = if t.word == "single" {
1786 Num::Val(1)
1787 } else {
1788 parse_num(&t.word)
1789 };
1790 // "add|write a line saying hello" (sc#349): no count is measured, but the
1791 // text it names is required (or uncertain), never dropped
1792 if t.word == "line" && i > 0 && matches!(toks[i - 1].word.as_str(), "a" | "an") {
1793 match said_clause(goal, &toks, i) {
1794 Some(Ok((phrase, end))) => {
1795 if !phrases.contains(&phrase) {
1796 phrases.push(phrase);
1797 }
1798 mark_bytes(&mut handled, &toks, toks[i].end, end);
1799 }
1800 Some(Err(())) => bad(&mut unsure, i + 1, false),
1801 None => {}
1802 }
1803 continue;
1804 }
1805 let (Num::Val(v), Some(noun)) = (num, toks.get(i + 1).map(|t| t.word.as_str())) else {
1806 continue;
1807 };
1808 if !matches!(noun, "line" | "lines") || handled.contains(&(i + 1)) {
1809 continue;
1810 }
1811 // "N lines at least" is a lower bound; "at most" and the like stay uncertain.
1812 let at = toks.get(i + 2).map(|t| t.word.as_str());
1813 let bound = at == Some("at") && toks.get(i + 3).is_some_and(|t| t.word == "least");
1814 let loose = at == Some("at")
1815 && toks
1816 .get(i + 3)
1817 .is_some_and(|t| matches!(t.word.as_str(), "most" | "max" | "the"));
1818 let tail_ok = !loose
1819 && (qualifier_ok(&toks, i + 1)
1820 || toks
1821 .get(i + 2)
1822 .is_some_and(|t| LINE_TAILS.contains(&t.word.as_str())));
1823 if tail_ok {
1824 add(
1825 &mut counts,
1826 Requirement::AddedLines {
1827 n: v,
1828 exact: exact && !bound,
1829 prior: None,
1830 },
1831 );
1832 handled.extend(s..=i + 1 + if bound { 2 } else { 0 });
1833 // "one line that says|reads \"S\"", "one line saying \"S\"" (sc#336):
1834 // that line holds S. A final . ! ? inside quotes that close the goal
1835 // sentence is the goal's own punctuation and is not required.
1836 // A saying clause on a counted line is never dropped: exactly one line
1837 // with no bound reads S; any other count, or a bound ("one line at
1838 // least saying S", the clause read after "at least"), is uncertain
1839 // (sc#349).
1840 if let Some(said) = said_clause(goal, &toks, i + 1 + if bound { 2 } else { 0 }) {
1841 match said {
1842 Ok((phrase, end)) if v == 1 && !bound => {
1843 if !phrases.contains(&phrase) {
1844 phrases.push(phrase);
1845 }
1846 mark_bytes(&mut handled, &toks, toks[i + 1].end, end);
1847 }
1848 _ => bad(&mut unsure, i + 2, false),
1849 }
1850 }
1851 }
1852 }
1853
1854 // ---- one sentence: "a one-sentence note", "a single sentence", "just one
1855 // sentence" (sc#336): the whole file is exactly one sentence ----
1856 let lead = |i: Option<usize>| i.map(|i| toks[i].word.as_str());
1857 let one_sentence = |s: usize| -> Option<usize> {
1858 let w = toks[s].word.as_str();
1859 if matches!(w, "one-sentence" | "single-sentence") {
1860 Some(s)
1861 } else if w == "sentence"
1862 && s >= 1
1863 && (toks[s - 1].word == "single"
1864 && matches!(lead(s.checked_sub(2)), Some("a" | "one" | "just" | "only"))
1865 || toks[s - 1].word == "one"
1866 && matches!(lead(s.checked_sub(2)), Some("just" | "only" | "exactly")))
1867 {
1868 Some(s - 1)
1869 } else {
1870 None
1871 }
1872 };
1873 let phrases_at: Vec<(usize, usize)> = (0..n)
1874 .filter_map(|s| one_sentence(s).map(|start| (start, s)))
1875 .collect();
1876 // The whole file only: nothing anywhere in the goal names a part of it, an
1877 // edit or addition to a file that may hold more ("update README.md with a
1878 // one-sentence summary", "... Append a goodbye."), or a second sentence
1879 // ("a one-sentence abstract and a one-sentence conclusion").
1880 let part = phrases_at.len() > 1
1881 || toks.iter().any(|t| {
1882 matches!(
1883 t.word.as_str(),
1884 "each"
1885 | "every"
1886 | "per"
1887 | "paragraph"
1888 | "paragraphs"
1889 | "line"
1890 | "lines"
1891 | "add"
1892 | "append"
1893 | "insert"
1894 | "prepend"
1895 | "update"
1896 | "replace"
1897 | "rewrite"
1898 | "edit"
1899 | "modify"
1900 | "change"
1901 | "shorten"
1902 | "put"
1903 | "place"
1904 | "top"
1905 | "bottom"
1906 | "beginning"
1907 | "header"
1908 | "footer"
1909 | "intro"
1910 | "introduction"
1911 | "title"
1912 | "heading"
1913 ) || SECTION_NOUNS.contains(&t.word.as_str())
1914 });
1915 for (start, s) in phrases_at {
1916 if handled.contains(&start) {
1917 continue;
1918 }
1919 // "a one-sentence note"; "one-sentence notes" may be many
1920 let one = start < s || matches!(lead(start.checked_sub(1)), Some("a" | "an"));
1921 if one && !part && !negated_before(&toks, start) {
1922 add(&mut counts, Requirement::SingleSentence);
1923 handled.extend(start..=s);
1924 } else {
1925 bad(&mut unsure, start, true);
1926 }
1927 }
1928
1929 // ---- fenced code blocks: "include three separate fenced code examples" ----
1930 for i in 0..n {
1931 let Num::Val(v) = parse_num(&toks[i].word) else {
1932 continue;
1933 };
1934 if handled.contains(&i) {
1935 continue;
1936 }
1937 let Some(j) = (i + 1..=i + 4).find(|&j| {
1938 toks.get(j)
1939 .is_some_and(|t| CODE_NOUNS.contains(&t.word.as_str()))
1940 }) else {
1941 continue;
1942 };
1943 let between = &toks[i + 1..j];
1944 if !between.iter().all(|t| CODE_ADJ.contains(&t.word.as_str()))
1945 || !between
1946 .iter()
1947 .any(|t| matches!(t.word.as_str(), "fenced" | "code"))
1948 {
1949 continue;
1950 }
1951 let tail_ok = qualifier_ok(&toks, j)
1952 || toks.get(j + 1).is_some_and(|t| {
1953 matches!(
1954 t.word.as_str(),
1955 "introduced" | "showing" | "demonstrating" | "illustrating"
1956 )
1957 });
1958 if !tail_ok {
1959 continue;
1960 }
1961 // The direction: a cue ending right before the number, else a plain
1962 // "include|add|put|provide ... N" (at least N).
1963 let mut dir_adj: Option<(usize, Dir, i64)> = None;
1964 for len in 1..=3usize {
1965 if i >= len {
1966 if let Some((l, d, a)) = match_cue(&toks, i - len, false) {
1967 if l == len {
1968 dir_adj = Some((len, d, a));
1969 break;
1970 }
1971 }
1972 }
1973 }
1974 let start = match dir_adj {
1975 Some((len, _, _)) => i - len,
1976 None => {
1977 let mut k = i;
1978 while k > 0 && matches!(toks[k - 1].word.as_str(), "a" | "an" | "the" | "separate")
1979 {
1980 k -= 1;
1981 }
1982 if k > 0 && CODE_VERBS.contains(&toks[k - 1].word.as_str()) {
1983 i
1984 } else {
1985 continue;
1986 }
1987 }
1988 };
1989 let (dir, adj) = dir_adj.map_or((Dir::Min, 0), |(_, d, a)| (d, a));
1990 let v = v as i64 + adj;
1991 if dir == Dir::Min && v >= 1 && !negated_before(&toks, start) {
1992 add(
1993 &mut counts,
1994 Requirement::MinItems(ItemKind::CodeBlocks, v as usize),
1995 );
1996 handled.extend(start..=j);
1997 }
1998 }
1999
2000 // ---- section titles: "sections titled A, B and C", "sections: A, B and C" ----
2001 for k in 0..n {
2002 let w = toks[k].word.as_str();
2003 let tw = |i: usize| toks[i].word.as_str();
2004 // "sections titled", and (sc#331, quoted titles only) "section is titled",
2005 // "one section must|should|will|shall|can be titled".
2006 let titled_at = if !matches!(w, "titled" | "named" | "called" | "entitled") || k < 1 {
2007 None
2008 } else if SECTION_NOUNS.contains(&tw(k - 1)) {
2009 Some((k - 1, false))
2010 } else if k >= 2 && matches!(tw(k - 1), "is" | "are") && SECTION_NOUNS.contains(&tw(k - 2))
2011 {
2012 Some((k - 2, true))
2013 } else if k >= 3
2014 && tw(k - 1) == "be"
2015 && matches!(tw(k - 2), "must" | "should" | "will" | "shall" | "can")
2016 && SECTION_NOUNS.contains(&tw(k - 3))
2017 {
2018 Some((k - 3, true))
2019 } else {
2020 None
2021 };
2022 let titled = titled_at.is_some();
2023 let colon = SECTION_NOUNS.contains(&w) && toks[k].raw.ends_with(':');
2024 if !titled && !colon {
2025 continue;
2026 }
2027 let noun_at = titled_at.map_or(k, |x| x.0);
2028 let needs_quotes = titled_at.is_some_and(|x| x.1);
2029 // The new forms are read only for one plain, unconditional title list:
2030 // not "each|every|all|any section is titled", not "... if needed".
2031 // The whole sentence is scanned, past commas and semicolons:
2032 // "titled \"X\", unless ...", "If needed, one section ...".
2033 // The quoted titles themselves ("When to Plant", "What If") are not hedges.
2034 let title_bytes = {
2035 let from = toks[k].end;
2036 from..from + leading_quoted_items(list_region(goal, from)).1
2037 };
2038 let hedged = needs_quotes && {
2039 (noun_at >= 1
2040 && matches!(
2041 toks[noun_at - 1].word.as_str(),
2042 "each" | "every" | "all" | "any"
2043 ))
2044 || toks[sentence_of(&toks, noun_at)].iter().any(|t| {
2045 !title_bytes.contains(&t.start)
2046 && matches!(
2047 t.word.as_str(),
2048 "if" | "unless"
2049 | "optionally"
2050 | "optional"
2051 | "may"
2052 | "might"
2053 | "when"
2054 | "whenever"
2055 | "perhaps"
2056 | "maybe"
2057 )
2058 })
2059 };
2060 let declared_at = [1usize, 2].into_iter().find_map(|d| {
2061 let p = noun_at.checked_sub(d)?;
2062 matches!(parse_num(&toks[p].word), Num::Val(_)).then_some(p)
2063 });
2064 let declared = declared_at.and_then(|p| match parse_num(&toks[p].word) {
2065 Num::Val(v) => Some(v),
2066 _ => None,
2067 });
2068 let region = list_region(goal, toks[k].end);
2069 let (quotes, quotes_end) = leading_quoted_items(region);
2070 let level = (titled && noun_at >= 1)
2071 .then(|| level_adj(&toks[noun_at - 1].word))
2072 .flatten();
2073 let quoted_list = !quotes.is_empty();
2074 let titles: Vec<String> = if quotes.is_empty() {
2075 split_list(region).iter().map(|t| trim_title(t)).collect()
2076 } else {
2077 quotes
2078 };
2079 let ok = !negated_before(&toks, noun_at)
2080 && !titles.is_empty()
2081 && titles.len() <= 40
2082 && titles
2083 .iter()
2084 .all(|t| !t.is_empty() && t.split_whitespace().count() <= 8)
2085 && (quoted_list || !titles.iter().any(|t| has_count_and_noun(t)))
2086 && (quoted_list || !needs_quotes)
2087 && !hedged
2088 && declared.is_none_or(|d| d == titles.len());
2089 if ok {
2090 let seen = match level {
2091 Some(l) => {
2092 let at = level_headings.iter().position(|x| x.0 == l);
2093 let slot = match at {
2094 Some(p) => &mut level_headings[p].1,
2095 None => {
2096 level_headings.push((l, Vec::new()));
2097 &mut level_headings.last_mut().expect("just pushed").1
2098 }
2099 };
2100 slot
2101 }
2102 None => &mut headings,
2103 };
2104 for t in titles {
2105 if !seen.contains(&t) {
2106 seen.push(t);
2107 }
2108 }
2109 let from = declared_at.unwrap_or(if level.is_some() {
2110 noun_at - 1
2111 } else {
2112 noun_at
2113 });
2114 handled.extend(from..=k);
2115 // Quoted titles consume only the quoted list; text after it is read on its own.
2116 let upto = if quotes_end > 0 {
2117 quotes_end
2118 } else {
2119 region.len()
2120 };
2121 mark_bytes(&mut handled, &toks, toks[k].end, toks[k].end + upto);
2122 } else {
2123 bad(&mut unsure, noun_at.min(k), false);
2124 }
2125 }
2126
2127 // ---- topics: "covers A, B and C" ----
2128 // The topics of the last counted list, for the forms a later sentence ties
2129 // to them by position ("withdrew ... for the third").
2130 let mut counted_topics: Vec<usize> = Vec::new();
2131 for k in 0..n {
2132 let w = toks[k].word.as_str();
2133 let starts_sentence = k == 0 || toks[k - 1].raw.ends_with(['.', '!', '?']);
2134 let key = matches!(w, "covers" | "covering")
2135 || (w == "cover"
2136 && k >= 1
2137 && matches!(
2138 toks[k - 1].word.as_str(),
2139 "to" | "should" | "must" | "will" | "can" | "also" | "shall" | "would" | "and"
2140 ));
2141 // "cover|covers|covering N topics: a, b and c" (sc#332): the count must
2142 // equal the list, which ends with the item after its "and" or "or".
2143 let counted = matches!(w, "cover" | "covers" | "covering")
2144 && (key || starts_sentence)
2145 && matches!(toks.get(k + 2), Some(t) if matches!(t.word.as_str(), "topics" | "topic") && t.raw.ends_with(':'));
2146 if counted {
2147 let declared = match parse_num(&toks[k + 1].word) {
2148 Num::Val(v) => Some(v),
2149 _ => None,
2150 };
2151 let region = closed_list(list_region(goal, toks[k + 2].end)).unwrap_or("");
2152 let items: Vec<String> = split_list(region).iter().map(|t| trim_title(t)).collect();
2153 let ok = !region.is_empty()
2154 && declared == Some(items.len())
2155 && !negated_before(&toks, k)
2156 && items.len() <= 12
2157 && !items.iter().any(|t| has_count_and_noun(t))
2158 && items
2159 .iter()
2160 .all(|t| (1..=4).contains(&content_words(t).len()));
2161 if ok {
2162 counted_topics.clear();
2163 for t in items {
2164 let at = topics.iter().position(|x| *x == t).unwrap_or_else(|| {
2165 topics.push(t);
2166 topics.len() - 1
2167 });
2168 counted_topics.push(at);
2169 }
2170 handled.extend(k..=k + 2);
2171 mark_bytes(
2172 &mut handled,
2173 &toks,
2174 toks[k + 2].end,
2175 toks[k + 2].end + region.len(),
2176 );
2177 } else {
2178 bad(&mut unsure, k, false);
2179 }
2180 continue;
2181 }
2182 if !key {
2183 continue;
2184 }
2185 let region = list_region(goal, toks[k].end);
2186 let items = split_list(region);
2187 let ok = !negated_before(&toks, k)
2188 && !items.iter().any(|t| has_count_and_noun(t))
2189 && !items.is_empty()
2190 && items.len() <= 12
2191 && items.iter().all(|t| {
2192 let c = content_words(t).len();
2193 (1..=4).contains(&c)
2194 });
2195 if ok {
2196 for t in items {
2197 let t = trim_title(&t);
2198 if !topics.contains(&t) {
2199 topics.push(t);
2200 }
2201 }
2202 handled.insert(k);
2203 mark_bytes(&mut handled, &toks, toks[k].end, toks[k].end + region.len());
2204 } else {
2205 bad(&mut unsure, k, false);
2206 }
2207 }
2208
2209 // Forms a goal ties to a counted topic by position (sc#332): "for example
2210 // interests or interested for the first one, ..., withdrew or withdrawing
2211 // for the third". A form the word-form rule already accepts is not added.
2212 if !counted_topics.is_empty() {
2213 for (at, forms) in positional_forms(goal, counted_topics.len()) {
2214 let i = counted_topics[at];
2215 let (topic, _) = topic_forms(&topics[i]);
2216 let words = content_words(topic);
2217 // Only a form of this topic: one word, the topic one word, the same
2218 // first three letters, and not already matched by the word-form rule.
2219 let [word] = words.as_slice() else {
2220 continue;
2221 };
2222 let keys = word_keys(word, true);
2223 let extra: Vec<String> = forms
2224 .into_iter()
2225 .filter(|f| {
2226 f.get(..3).is_some_and(|p| word.starts_with(p))
2227 && !word_keys(f, false).iter().any(|k| keys.contains(k))
2228 })
2229 .collect();
2230 if !extra.is_empty() {
2231 topics[i] = format!("{topic} (or {})", extra.join(", "));
2232 }
2233 }
2234 }
2235
2236 // ---- required words and phrases ----
2237 // `include|contain the phrase "X"` (one quoted phrase, ending its clause).
2238 let low = goal.to_ascii_lowercase();
2239 for key in ["include the phrase \"", "contain the phrase \""] {
2240 let mut from = 0;
2241 while let Some(i) = low[from..].find(key) {
2242 let key_at = from + i;
2243 let start = key_at + key.len();
2244 let Some(len) = low[start..].find('"') else {
2245 break;
2246 };
2247 let end = start + len;
2248 let before_n = toks.iter().take_while(|t| t.start < key_at).count();
2249 let negated = negated_before(&toks, before_n);
2250 let after = low[end + 1..].split_whitespace().next();
2251 let closes_clause = low[end + 1..].starts_with([',', '.', ';', ':', '!', '?', ')'])
2252 || after.is_none_or(|nx| CLAUSE_JOINERS.contains(&clean(nx)));
2253 if len > 0
2254 && !negated
2255 && closes_clause
2256 && goal.is_char_boundary(start)
2257 && goal.is_char_boundary(end)
2258 {
2259 let p = goal[start..end].to_string();
2260 if !phrases.contains(&p) {
2261 phrases.push(p);
2262 }
2263 if let Some(t) = toks.iter().position(|t| t.start == key_at) {
2264 handled.insert(t);
2265 }
2266 mark_bytes(&mut handled, &toks, key_at, end + 1);
2267 }
2268 from = end + 1;
2269 }
2270 }
2271 // Any other `include|contain|use|mention the word(s)|term(s)|phrase(s) ...`.
2272 for k in 0..n {
2273 if !matches!(
2274 toks[k].word.as_str(),
2275 "include"
2276 | "includes"
2277 | "contain"
2278 | "contains"
2279 | "use"
2280 | "uses"
2281 | "mention"
2282 | "mentions"
2283 ) || toks.get(k + 1).map(|t| t.word.as_str()) != Some("the")
2284 {
2285 continue;
2286 }
2287 // "use the exact words X and Y" (sc#333): an adjective may sit before the noun.
2288 let q = if toks
2289 .get(k + 2)
2290 .is_some_and(|t| matches!(t.word.as_str(), "exact" | "following" | "specific" | "same"))
2291 {
2292 k + 3
2293 } else {
2294 k + 2
2295 };
2296 let Some(kind) = toks.get(q).map(|t| t.word.as_str()) else {
2297 continue;
2298 };
2299 if !matches!(
2300 kind,
2301 "word" | "words" | "term" | "terms" | "phrase" | "phrases"
2302 ) {
2303 continue;
2304 }
2305 if handled.contains(&k) {
2306 continue;
2307 }
2308 if kind == "phrase" {
2309 // The singular quoted form is the block above; anything it refused stays uncertain.
2310 bad(&mut unsure, k, false);
2311 continue;
2312 }
2313 let full = list_region(goal, toks[q].end);
2314 // "... headlamp and first-aid somewhere in the list": a place that is the
2315 // whole document is not part of the list; any other place is uncertain.
2316 let (region, place_ok) = match ["somewhere", "anywhere"]
2317 .iter()
2318 .filter_map(|p| full.to_ascii_lowercase().find(&format!(" {p}")))
2319 .min()
2320 {
2321 Some(at) => (&full[..at], whole_document_place(&full[at..])),
2322 None => (full, true),
2323 };
2324 let quotes = quoted_items(region);
2325 let (items, tail_ok) = if quotes.is_empty() {
2326 let items: Vec<String> = split_list(region).iter().map(|t| trim_title(t)).collect();
2327 let single = items
2328 .iter()
2329 .all(|t| !t.is_empty() && t.split_whitespace().count() == 1);
2330 (items, single && kind != "phrases")
2331 } else {
2332 let last_q = region.rfind(['"', '\u{201D}']).unwrap_or(0);
2333 let tail = region[last_q + 1..].trim().to_ascii_lowercase();
2334 let tail_word = tail.split_whitespace().next().map(clean).unwrap_or("");
2335 (
2336 quotes,
2337 tail.is_empty() || CLAUSE_JOINERS.contains(&tail_word),
2338 )
2339 };
2340 let ends_ok = list_ends_cleanly(&goal[toks[q].end + full.len()..], "");
2341 if !negated_before(&toks, k)
2342 && tail_ok
2343 && place_ok
2344 && ends_ok
2345 && !is_choice(region)
2346 && !items.is_empty()
2347 && items.len() <= 20
2348 {
2349 let dst = if kind == "phrases" {
2350 &mut phrases
2351 } else {
2352 &mut words
2353 };
2354 for t in items {
2355 if !dst.contains(&t) {
2356 dst.push(t);
2357 }
2358 }
2359 handled.extend(k..=q);
2360 mark_bytes(&mut handled, &toks, toks[q].end, toks[q].end + full.len());
2361 } else {
2362 bad(&mut unsure, k, false);
2363 }
2364 }
2365 // "make sure|be sure|ensure|check that the words X and Y [both|all] appear|
2366 // show up|are used [somewhere in it]" (sc#333).
2367 for k in 1..n {
2368 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
2369 if w(k) != Some("the")
2370 || !matches!(w(k - 1), Some("sure" | "ensure" | "that"))
2371 || handled.contains(&k)
2372 {
2373 continue;
2374 }
2375 let q = if matches!(w(k + 1), Some("exact" | "following" | "specific")) {
2376 k + 2
2377 } else {
2378 k + 1
2379 };
2380 if !matches!(w(q), Some("word" | "words" | "term" | "terms")) {
2381 continue;
2382 }
2383 match words_must_appear(goal, &toks, k, q) {
2384 Some((items, last)) => {
2385 for t in items {
2386 if !words.contains(&t) {
2387 words.push(t);
2388 }
2389 }
2390 handled.extend(k - 1..=last);
2391 }
2392 None => bad(&mut unsure, k - 1, false),
2393 }
2394 }
2395 // "must|should|will|to name|mention Priya, Tomas and Wen [by name]": a list
2396 // of single capitalised words (names) is RequiredWords; a list that mixes
2397 // names and other words, offers a choice ("Priya or Tomas"), or carries a
2398 // count or scope on ("at least twice", "Dr. Smith") is uncertain; a list
2399 // without names ("the file README.md", "2024") stays silent (sc#333).
2400 for k in 1..n {
2401 if !matches!(
2402 toks[k].word.as_str(),
2403 "name" | "names" | "mention" | "mentions"
2404 ) || !matches!(
2405 toks[k - 1].word.as_str(),
2406 "must" | "should" | "will" | "shall" | "to" | "also"
2407 ) || handled.contains(&k)
2408 || ends_clause(&toks[k].raw)
2409 {
2410 continue;
2411 }
2412 let full = list_region(goal, toks[k].end);
2413 // ", and the file needs ..." or ", and I want ..." starts a new clause;
2414 // ", and Wen" is the last name.
2415 let region = match full.match_indices(", and ").find(|(i, m)| {
2416 let rest = &full[i + m.len()..];
2417 rest.starts_with(|c: char| c.is_lowercase()) || rest.starts_with("I ")
2418 }) {
2419 Some((i, _)) => &full[..i],
2420 None => full,
2421 };
2422 let trimmed = region.trim_end();
2423 let list = trimmed
2424 .strip_suffix(" by name")
2425 .or_else(|| trimmed.strip_suffix(" by name,"))
2426 .unwrap_or(trimmed);
2427 let items: Vec<String> = split_list(list).iter().map(|t| trim_title(t)).collect();
2428 let capital = |t: &String| t.starts_with(|c: char| c.is_ascii_uppercase());
2429 let names = !items.is_empty()
2430 && items.len() <= 20
2431 && items
2432 .iter()
2433 .all(|t| capital(t) && t.split_whitespace().count() == 1);
2434 let last_item = items.last().map_or("", String::as_str);
2435 let ends_ok = list_ends_cleanly(&goal[toks[k].end + region.len()..], last_item);
2436 if names && ends_ok && !is_choice(list) && !negated_before(&toks, k) {
2437 for t in items {
2438 if !words.contains(&t) {
2439 words.push(t);
2440 }
2441 }
2442 handled.insert(k);
2443 mark_bytes(&mut handled, &toks, toks[k].end, toks[k].end + region.len());
2444 } else if items.iter().any(capital) {
2445 bad(&mut unsure, k - 1, false);
2446 }
2447 }
2448 // The singular phrase key that matched no quoted text at all.
2449 for k in 0..n {
2450 if toks[k].word.starts_with("includ") || toks[k].word.starts_with("contain") {
2451 let w2 = |d: usize| toks.get(k + d).map(|t| t.word.as_str());
2452 if w2(1) == Some("the") && w2(2) == Some("phrase") && !handled.contains(&k) {
2453 bad(&mut unsure, k, false);
2454 }
2455 }
2456 }
2457
2458 // ---- first-line heading: "start with a [markdown] [level-N] heading [line]
2459 // [that begins with "# "]" ----
2460 let mut first_heading: Option<Option<usize>> = None;
2461 for v in 0..n {
2462 let w = |i: usize| toks.get(i).map(|t| t.word.as_str());
2463 if handled.contains(&v)
2464 || !matches!(
2465 w(v),
2466 Some("start" | "starts" | "begin" | "begins" | "open" | "opens")
2467 )
2468 || w(v + 1) != Some("with")
2469 || w(v + 2) != Some("a")
2470 || (v..v + 2).any(|i| ends_clause(&toks[i].raw))
2471 {
2472 continue;
2473 }
2474 let mut k = v + 3;
2475 if w(k) == Some("markdown") && !ends_clause(&toks[k].raw) {
2476 k += 1;
2477 }
2478 let adj = w(k).and_then(level_adj);
2479 if adj.is_some() && !ends_clause(&toks[k].raw) {
2480 k += 1;
2481 }
2482 if w(k) != Some("heading") {
2483 // "start with a **heading**", "start with a short heading": a heading
2484 // wording this recognizer does not read is uncertain, never silent.
2485 if (v + 3..=v + 5).any(|i| toks.get(i).is_some_and(|t| t.norm.starts_with("heading"))) {
2486 bad(&mut unsure, v, false);
2487 }
2488 continue;
2489 }
2490 if w(k + 1) == Some("line") && !ends_clause(&toks[k].raw) {
2491 k += 1;
2492 }
2493 if negated_before(&toks, v) {
2494 bad(&mut unsure, v, false);
2495 continue;
2496 }
2497 // The heading clause must END its sentence: anything after it in the same
2498 // sentence ("and keep it brief", ", then a table") is left to the refusal below,
2499 // so no sibling constraint is swallowed unchecked.
2500 let sentence_end = |raw: &str| raw.ends_with(['.', '!', '?']);
2501 let found = if sentence_end(&toks[k].raw) || k + 1 == n {
2502 Some((adj, k))
2503 } else if matches!(w(k + 1), Some("that" | "which"))
2504 && matches!(w(k + 2), Some("begins" | "starts" | "begin" | "start"))
2505 && w(k + 3) == Some("with")
2506 && (k..k + 3).all(|i| !ends_clause(&toks[i].raw))
2507 {
2508 // The marker: a quoted run of 1 to 6 `#` and one space, then the end of
2509 // the clause. Anything else ("#" alone, "a hash", a qualifier) is uncertain.
2510 let from = toks[k + 3].end;
2511 let rest = &goal[from..];
2512 let lead = rest.len() - rest.trim_start().len();
2513 let mut cs = rest[lead..].char_indices();
2514 let marker = cs.next().and_then(|(_, q)| {
2515 let close: &[char] = match q {
2516 '"' => &['"'],
2517 '\u{201C}' => &['\u{201D}', '"'],
2518 '\'' => &['\''],
2519 '`' => &['`'],
2520 _ => return None,
2521 };
2522 let body = &rest[lead + q.len_utf8()..];
2523 let h = body.bytes().take_while(|&b| b == b'#').count();
2524 let after_space = body[h..].strip_prefix(' ')?;
2525 let c = after_space.chars().next().filter(|c| close.contains(c))?;
2526 let end = from + rest.len() - after_space.len() + c.len_utf8();
2527 let tail_ok =
2528 goal[end..].trim_end().is_empty() || goal[end..].starts_with(['.', '!', '?']);
2529 ((1..=6).contains(&h) && tail_ok).then_some((h, end))
2530 });
2531 match marker {
2532 Some((h, end)) if adj.is_none_or(|a| a == h) => {
2533 mark_bytes(&mut handled, &toks, from, end);
2534 let last = (0..n).rev().find(|&i| toks[i].start < end).unwrap_or(k + 3);
2535 Some((Some(h), last))
2536 }
2537 _ => None,
2538 }
2539 } else {
2540 None
2541 };
2542 match found {
2543 Some((level, last)) if first_heading.is_none_or(|f| f == level) => {
2544 first_heading = Some(level);
2545 handled.extend(v..=last.max(k));
2546 }
2547 _ => bad(&mut unsure, v, false),
2548 }
2549 }
2550
2551 // ---- candidates the recognizers above did not claim ----
2552 for s in 0..n {
2553 if handled.contains(&s) {
2554 continue;
2555 }
2556 // cue N <noun> (an adjective may sit between), in the emphasis-stripped view
2557 let after = |i: usize| toks.get(i).map(|t| t.norm.as_str());
2558 let cue = match_cue(&toks, s, true)
2559 .map(|c| c.0)
2560 .or_else(|| VAGUE.contains(&toks[s].norm.as_str()).then_some(1));
2561 if let Some(len) = cue {
2562 let vague = len == 1 && VAGUE.contains(&toks[s].norm.as_str());
2563 let i = s + len;
2564 let reach = if vague { 4 } else { 2 };
2565 let num_at = after(i).map(parse_num);
2566 let looks_numeric = matches!(num_at, Some(Num::Val(_)) | Some(Num::Bad));
2567 let noun_near =
2568 (i + 1..=i + reach).any(|j| after(j).is_some_and(|w| NOUNS.contains(&w)));
2569 // "under three sections titled A, B and C": a preposition before a
2570 // count a recognizer already read (sc#331).
2571 let organise = |m: usize| {
2572 toks.get(m).is_some_and(|t| {
2573 matches!(
2574 t.word.as_str(),
2575 "organise"
2576 | "organize"
2577 | "structure"
2578 | "arrange"
2579 | "divide"
2580 | "group"
2581 | "split"
2582 | "sort"
2583 )
2584 })
2585 };
2586 let under_read = toks[s].norm == "under"
2587 && handled.contains(&i)
2588 && ((s >= 1 && organise(s - 1)) || (s >= 2 && organise(s - 2)));
2589 // a bound cue and a number nothing above read: read or UNCERTAIN, never
2590 // ignored ("at most 40 please", "fix at least 2 typos") (#344)
2591 let unread_bound =
2592 !vague && matches!(num_at, Some(Num::Val(_))) && !handled.contains(&i);
2593 if ((looks_numeric && (noun_near || num_at == Some(Num::Bad))) || unread_bound)
2594 && !under_read
2595 {
2596 bad(&mut unsure, s, true);
2597 continue;
2598 }
2599 }
2600 // "20 or more lines" / "20+ lines" in emphasis, and "35-line"
2601 let w = toks[s].norm.as_str();
2602 if let Some((a, b)) = w.split_once('-') {
2603 let noun = b.trim_end_matches('s');
2604 if matches!(parse_num(a), Num::Val(_))
2605 && (NOUNS.contains(&format!("{noun}s").as_str()) || NOUNS.contains(&noun))
2606 {
2607 bad(&mut unsure, s, true);
2608 continue;
2609 }
2610 }
2611 let trailing_plus =
2612 w.ends_with('+') && matches!(parse_num(w.trim_end_matches('+')), Num::Val(_));
2613 let or_more = matches!(parse_num(w), Num::Val(_))
2614 && after(s + 1) == Some("or")
2615 && matches!(after(s + 2), Some("more" | "fewer" | "less"));
2616 if (trailing_plus || or_more)
2617 && (s + 1..=s + 3).any(|j| after(j).is_some_and(|x| NOUNS.contains(&x)))
2618 {
2619 bad(&mut unsure, s, true);
2620 }
2621 }
2622
2623 // ---- safety net: a countable noun with a number, or a quantity or list cue ----
2624 // Anything the recognizers above did not consume is UNCERTAIN, so a
2625 // wording nobody listed is reported instead of silently passing.
2626 let nm = |i: usize| toks.get(i).map(|t| t.norm.as_str());
2627 for (i, tk) in toks.iter().enumerate() {
2628 let w = tk.norm.as_str();
2629 // N [adjective] [adjective] <noun>
2630 if let Num::Val(_) = parse_num(w) {
2631 let next = nm(i + 1).unwrap_or("");
2632 let pronoun = w == "one"
2633 && matches!(
2634 next,
2635 "of" | "can"
2636 | "may"
2637 | "should"
2638 | "must"
2639 | "that"
2640 | "who"
2641 | "which"
2642 | "is"
2643 | "to"
2644 | "more"
2645 | "another"
2646 | "thing"
2647 | "day"
2648 | "time"
2649 );
2650 // "twelve of them", "12 or more of them": a count of items the goal does not name.
2651 let of_at = if nm(i + 1) == Some("or")
2652 && matches!(nm(i + 2), Some("more" | "fewer" | "less"))
2653 {
2654 i + 3
2655 } else {
2656 i + 1
2657 };
2658 if w != "one"
2659 && nm(of_at) == Some("of")
2660 && matches!(nm(of_at + 1), Some("them" | "these" | "those"))
2661 && !handled.contains(&i)
2662 {
2663 bad(&mut unsure, i, true);
2664 }
2665 if !pronoun {
2666 // The window never crosses the end of a sentence.
2667 let stop = (i..i + 4)
2668 .find(|&k| {
2669 toks.get(k)
2670 .is_some_and(|t| t.raw.ends_with(['.', '!', '?']))
2671 })
2672 .map_or(i + 4, |k| k.max(i + 1));
2673 if let Some(j) = (i + 1..=stop).find(|&j| nm(j).is_some_and(|x| NOUNS.contains(&x)))
2674 {
2675 if !handled.contains(&i) || !handled.contains(&j) {
2676 bad(&mut unsure, i, true);
2677 }
2678 }
2679 }
2680 }
2681 // "2-3 lines" (a range), "three-plus sections", "a dozen lines"
2682 if !handled.contains(&i) {
2683 let noun_next = (i + 1..=i + 2).any(|j| nm(j).is_some_and(|x| NOUNS.contains(&x)));
2684 let range = w.split_once('-').is_some_and(|(a, b)| {
2685 matches!(parse_num(a), Num::Val(_))
2686 && (matches!(parse_num(b), Num::Val(_)) || b == "plus")
2687 });
2688 if (range || matches!(w, "dozen" | "dozens")) && noun_next {
2689 bad(&mut unsure, i, true);
2690 }
2691 // "line count at least 40", "word count of 200"
2692 if w == "count"
2693 && i >= 1
2694 && nm(i - 1).is_some_and(|x| NOUNS.contains(&x) || matches!(x, "line" | "word"))
2695 && (i + 1..=i + 6).any(|j| matches!(nm(j).map(parse_num), Some(Num::Val(_))))
2696 {
2697 bad(&mut unsure, i - 1, true);
2698 }
2699 // a heading level adjective that no title list consumed
2700 if level_adj(w).is_some() && nm(i + 1).is_some_and(|x| SECTION_NOUNS.contains(&x)) {
2701 bad(&mut unsure, i, true);
2702 }
2703 }
2704 // quantity cues next to a countable noun: twice, minimum, "or more", ...
2705 let cue = matches!(
2706 w,
2707 "twice" | "thrice" | "minimum" | "maximum" | "limit" | "min" | "max"
2708 ) || (w == "or" && matches!(nm(i + 1), Some("more" | "fewer" | "less")))
2709 || (matches!(w, "longer" | "shorter") && nm(i + 1) == Some("than"));
2710 if cue && !handled.contains(&i) {
2711 let lo = i.saturating_sub(3);
2712 if (lo..=i + 3).any(|j| nm(j).is_some_and(|x| NOUNS.contains(&x))) {
2713 bad(&mut unsure, i.saturating_sub(1), true);
2714 }
2715 }
2716 // heading and word lists without a number
2717 let heading_list = matches!(w, "heading" | "headings")
2718 && (nm(i + 1) == Some("for")
2719 || tk.raw.ends_with(':')
2720 || (i >= 2
2721 && matches!(nm(i - 2), Some("a" | "the"))
2722 && i >= 3
2723 && matches!(
2724 nm(i - 3),
2725 Some(
2726 "needs"
2727 | "need"
2728 | "must"
2729 | "should"
2730 | "have"
2731 | "has"
2732 | "include"
2733 | "includes"
2734 | "contain"
2735 | "contains"
2736 | "with"
2737 | "and"
2738 )
2739 )));
2740 let word_list = matches!(w, "word" | "words")
2741 && (tk.raw.ends_with(':')
2742 || (i >= 1
2743 && matches!(
2744 nm(i - 1),
2745 Some(
2746 "these"
2747 | "following"
2748 | "those"
2749 | "the"
2750 | "key"
2751 | "exact"
2752 | "specific"
2753 | "same"
2754 )
2755 )));
2756 if (heading_list || word_list) && !handled.contains(&i) {
2757 bad(&mut unsure, i.saturating_sub(2), false);
2758 }
2759 }
2760
2761 let mut requirements = counts;
2762 if !headings.is_empty() {
2763 requirements.push(Requirement::RequiredHeadings(headings));
2764 }
2765 for (level, titles) in level_headings {
2766 requirements.push(Requirement::LevelHeadings { level, titles });
2767 }
2768 if !topics.is_empty() {
2769 requirements.push(Requirement::RequiredTopics(topics));
2770 }
2771 if !phrases.is_empty() {
2772 requirements.push(Requirement::RequiredPhrases(phrases));
2773 }
2774 if !words.is_empty() {
2775 requirements.push(Requirement::RequiredWords(words));
2776 }
2777 if let Some(level) = first_heading {
2778 requirements.push(Requirement::FirstLineHeading { level });
2779 }
2780 unsure.sort_by_key(|u| u.0);
2781 let mut uncertain: Vec<String> = Vec::new();
2782 let all: Vec<String> = unsure.into_iter().map(|u| u.1).collect();
2783 for t in &all {
2784 // A span inside a longer reported span is the same finding.
2785 let inside = all
2786 .iter()
2787 .any(|o| o.len() > t.len() && o.contains(t.as_str()));
2788 if !inside && !uncertain.contains(t) {
2789 uncertain.push(t.clone());
2790 }
2791 }
2792 Extraction {
2793 requirements,
2794 uncertain,
2795 }
2796}