github.com/bir3/gocompiler@v0.9.2202/src/go/doc/synopsis.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package doc
     6  
     7  import (
     8  	"github.com/bir3/gocompiler/src/go/doc/comment"
     9  	"strings"
    10  	"unicode"
    11  )
    12  
    13  // firstSentence returns the first sentence in s.
    14  // The sentence ends after the first period followed by space and
    15  // not preceded by exactly one uppercase letter.
    16  func firstSentence(s string) string {
    17  	var ppp, pp, p rune
    18  	for i, q := range s {
    19  		if q == '\n' || q == '\r' || q == '\t' {
    20  			q = ' '
    21  		}
    22  		if q == ' ' && p == '.' && (!unicode.IsUpper(pp) || unicode.IsUpper(ppp)) {
    23  			return s[:i]
    24  		}
    25  		if p == '。' || p == '.' {
    26  			return s[:i]
    27  		}
    28  		ppp, pp, p = pp, p, q
    29  	}
    30  	return s
    31  }
    32  
    33  // Synopsis returns a cleaned version of the first sentence in text.
    34  //
    35  // Deprecated: New programs should use [Package.Synopsis] instead,
    36  // which handles links in text properly.
    37  func Synopsis(text string) string {
    38  	var p Package
    39  	return p.Synopsis(text)
    40  }
    41  
    42  // IllegalPrefixes is a list of lower-case prefixes that identify
    43  // a comment as not being a doc comment.
    44  // This helps to avoid misinterpreting the common mistake
    45  // of a copyright notice immediately before a package statement
    46  // as being a doc comment.
    47  var IllegalPrefixes = []string{
    48  	"copyright",
    49  	"all rights",
    50  	"author",
    51  }
    52  
    53  // Synopsis returns a cleaned version of the first sentence in text.
    54  // That sentence ends after the first period followed by space and not
    55  // preceded by exactly one uppercase letter, or at the first paragraph break.
    56  // The result string has no \n, \r, or \t characters and uses only single
    57  // spaces between words. If text starts with any of the [IllegalPrefixes],
    58  // the result is the empty string.
    59  func (p *Package) Synopsis(text string) string {
    60  	text = firstSentence(text)
    61  	lower := strings.ToLower(text)
    62  	for _, prefix := range IllegalPrefixes {
    63  		if strings.HasPrefix(lower, prefix) {
    64  			return ""
    65  		}
    66  	}
    67  	pr := p.Printer()
    68  	pr.TextWidth = -1
    69  	d := p.Parser().Parse(text)
    70  	if len(d.Content) == 0 {
    71  		return ""
    72  	}
    73  	if _, ok := d.Content[0].(*comment.Paragraph); !ok {
    74  		return ""
    75  	}
    76  	d.Content = d.Content[:1]	// might be blank lines, code blocks, etc in “first sentence”
    77  	return strings.TrimSpace(string(pr.Text(d)))
    78  }