...

Source file src/go/ast/commentmap.go

Documentation: go/ast

     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 ast
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/token"
    11  	"sort"
    12  )
    13  
    14  type byPos []*CommentGroup
    15  
    16  func (a byPos) Len() int           { return len(a) }
    17  func (a byPos) Less(i, j int) bool { return a[i].Pos() < a[j].Pos() }
    18  func (a byPos) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    19  
    20  // sortComments sorts the list of comment groups in source order.
    21  func sortComments(list []*CommentGroup) {
    22  	// TODO(gri): Does it make sense to check for sorted-ness
    23  	//            first (because we know that sorted-ness is
    24  	//            very likely)?
    25  	if orderedList := byPos(list); !sort.IsSorted(orderedList) {
    26  		sort.Sort(orderedList)
    27  	}
    28  }
    29  
    30  // A CommentMap maps an AST node to a list of comment groups
    31  // associated with it. See NewCommentMap for a description of
    32  // the association.
    33  type CommentMap map[Node][]*CommentGroup
    34  
    35  func (cmap CommentMap) addComment(n Node, c *CommentGroup) {
    36  	list := cmap[n]
    37  	if len(list) == 0 {
    38  		list = []*CommentGroup{c}
    39  	} else {
    40  		list = append(list, c)
    41  	}
    42  	cmap[n] = list
    43  }
    44  
    45  type byInterval []Node
    46  
    47  func (a byInterval) Len() int { return len(a) }
    48  func (a byInterval) Less(i, j int) bool {
    49  	pi, pj := a[i].Pos(), a[j].Pos()
    50  	return pi < pj || pi == pj && a[i].End() > a[j].End()
    51  }
    52  func (a byInterval) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
    53  
    54  // nodeList returns the list of nodes of the AST n in source order.
    55  func nodeList(n Node) []Node {
    56  	var list []Node
    57  	Inspect(n, func(n Node) bool {
    58  		// don't collect comments
    59  		switch n.(type) {
    60  		case nil, *CommentGroup, *Comment:
    61  			return false
    62  		}
    63  		list = append(list, n)
    64  		return true
    65  	})
    66  	// Note: The current implementation assumes that Inspect traverses the
    67  	//       AST in depth-first and thus _source_ order. If AST traversal
    68  	//       does not follow source order, the sorting call below will be
    69  	//       required.
    70  	// sort.Sort(byInterval(list))
    71  	return list
    72  }
    73  
    74  // A commentListReader helps iterating through a list of comment groups.
    75  type commentListReader struct {
    76  	fset     *token.FileSet
    77  	list     []*CommentGroup
    78  	index    int
    79  	comment  *CommentGroup  // comment group at current index
    80  	pos, end token.Position // source interval of comment group at current index
    81  }
    82  
    83  func (r *commentListReader) eol() bool {
    84  	return r.index >= len(r.list)
    85  }
    86  
    87  func (r *commentListReader) next() {
    88  	if !r.eol() {
    89  		r.comment = r.list[r.index]
    90  		r.pos = r.fset.Position(r.comment.Pos())
    91  		r.end = r.fset.Position(r.comment.End())
    92  		r.index++
    93  	}
    94  }
    95  
    96  // A nodeStack keeps track of nested nodes.
    97  // A node lower on the stack lexically contains the nodes higher on the stack.
    98  type nodeStack []Node
    99  
   100  // push pops all nodes that appear lexically before n
   101  // and then pushes n on the stack.
   102  func (s *nodeStack) push(n Node) {
   103  	s.pop(n.Pos())
   104  	*s = append((*s), n)
   105  }
   106  
   107  // pop pops all nodes that appear lexically before pos
   108  // (i.e., whose lexical extent has ended before or at pos).
   109  // It returns the last node popped.
   110  func (s *nodeStack) pop(pos token.Pos) (top Node) {
   111  	i := len(*s)
   112  	for i > 0 && (*s)[i-1].End() <= pos {
   113  		top = (*s)[i-1]
   114  		i--
   115  	}
   116  	*s = (*s)[0:i]
   117  	return top
   118  }
   119  
   120  // NewCommentMap creates a new comment map by associating comment groups
   121  // of the comments list with the nodes of the AST specified by node.
   122  //
   123  // A comment group g is associated with a node n if:
   124  //
   125  //   - g starts on the same line as n ends
   126  //   - g starts on the line immediately following n, and there is
   127  //     at least one empty line after g and before the next node
   128  //   - g starts before n and is not associated to the node before n
   129  //     via the previous rules
   130  //
   131  // NewCommentMap tries to associate a comment group to the "largest"
   132  // node possible: For instance, if the comment is a line comment
   133  // trailing an assignment, the comment is associated with the entire
   134  // assignment rather than just the last operand in the assignment.
   135  func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap {
   136  	if len(comments) == 0 {
   137  		return nil // no comments to map
   138  	}
   139  
   140  	cmap := make(CommentMap)
   141  
   142  	// set up comment reader r
   143  	tmp := make([]*CommentGroup, len(comments))
   144  	copy(tmp, comments) // don't change incoming comments
   145  	sortComments(tmp)
   146  	r := commentListReader{fset: fset, list: tmp} // !r.eol() because len(comments) > 0
   147  	r.next()
   148  
   149  	// create node list in lexical order
   150  	nodes := nodeList(node)
   151  	nodes = append(nodes, nil) // append sentinel
   152  
   153  	// set up iteration variables
   154  	var (
   155  		p     Node           // previous node
   156  		pend  token.Position // end of p
   157  		pg    Node           // previous node group (enclosing nodes of "importance")
   158  		pgend token.Position // end of pg
   159  		stack nodeStack      // stack of node groups
   160  	)
   161  
   162  	for _, q := range nodes {
   163  		var qpos token.Position
   164  		if q != nil {
   165  			qpos = fset.Position(q.Pos()) // current node position
   166  		} else {
   167  			// set fake sentinel position to infinity so that
   168  			// all comments get processed before the sentinel
   169  			const infinity = 1 << 30
   170  			qpos.Offset = infinity
   171  			qpos.Line = infinity
   172  		}
   173  
   174  		// process comments before current node
   175  		for r.end.Offset <= qpos.Offset {
   176  			// determine recent node group
   177  			if top := stack.pop(r.comment.Pos()); top != nil {
   178  				pg = top
   179  				pgend = fset.Position(pg.End())
   180  			}
   181  			// Try to associate a comment first with a node group
   182  			// (i.e., a node of "importance" such as a declaration);
   183  			// if that fails, try to associate it with the most recent
   184  			// node.
   185  			// TODO(gri) try to simplify the logic below
   186  			var assoc Node
   187  			switch {
   188  			case pg != nil &&
   189  				(pgend.Line == r.pos.Line ||
   190  					pgend.Line+1 == r.pos.Line && r.end.Line+1 < qpos.Line):
   191  				// 1) comment starts on same line as previous node group ends, or
   192  				// 2) comment starts on the line immediately after the
   193  				//    previous node group and there is an empty line before
   194  				//    the current node
   195  				// => associate comment with previous node group
   196  				assoc = pg
   197  			case p != nil &&
   198  				(pend.Line == r.pos.Line ||
   199  					pend.Line+1 == r.pos.Line && r.end.Line+1 < qpos.Line ||
   200  					q == nil):
   201  				// same rules apply as above for p rather than pg,
   202  				// but also associate with p if we are at the end (q == nil)
   203  				assoc = p
   204  			default:
   205  				// otherwise, associate comment with current node
   206  				if q == nil {
   207  					// we can only reach here if there was no p
   208  					// which would imply that there were no nodes
   209  					panic("internal error: no comments should be associated with sentinel")
   210  				}
   211  				assoc = q
   212  			}
   213  			cmap.addComment(assoc, r.comment)
   214  			if r.eol() {
   215  				return cmap
   216  			}
   217  			r.next()
   218  		}
   219  
   220  		// update previous node
   221  		p = q
   222  		pend = fset.Position(p.End())
   223  
   224  		// update previous node group if we see an "important" node
   225  		switch q.(type) {
   226  		case *File, *Field, Decl, Spec, Stmt:
   227  			stack.push(q)
   228  		}
   229  	}
   230  
   231  	return cmap
   232  }
   233  
   234  // Update replaces an old node in the comment map with the new node
   235  // and returns the new node. Comments that were associated with the
   236  // old node are associated with the new node.
   237  func (cmap CommentMap) Update(old, new Node) Node {
   238  	if list := cmap[old]; len(list) > 0 {
   239  		delete(cmap, old)
   240  		cmap[new] = append(cmap[new], list...)
   241  	}
   242  	return new
   243  }
   244  
   245  // Filter returns a new comment map consisting of only those
   246  // entries of cmap for which a corresponding node exists in
   247  // the AST specified by node.
   248  func (cmap CommentMap) Filter(node Node) CommentMap {
   249  	umap := make(CommentMap)
   250  	Inspect(node, func(n Node) bool {
   251  		if g := cmap[n]; len(g) > 0 {
   252  			umap[n] = g
   253  		}
   254  		return true
   255  	})
   256  	return umap
   257  }
   258  
   259  // Comments returns the list of comment groups in the comment map.
   260  // The result is sorted in source order.
   261  func (cmap CommentMap) Comments() []*CommentGroup {
   262  	list := make([]*CommentGroup, 0, len(cmap))
   263  	for _, e := range cmap {
   264  		list = append(list, e...)
   265  	}
   266  	sortComments(list)
   267  	return list
   268  }
   269  
   270  func summary(list []*CommentGroup) string {
   271  	const maxLen = 40
   272  	var buf bytes.Buffer
   273  
   274  	// collect comments text
   275  loop:
   276  	for _, group := range list {
   277  		// Note: CommentGroup.Text() does too much work for what we
   278  		//       need and would only replace this innermost loop.
   279  		//       Just do it explicitly.
   280  		for _, comment := range group.List {
   281  			if buf.Len() >= maxLen {
   282  				break loop
   283  			}
   284  			buf.WriteString(comment.Text)
   285  		}
   286  	}
   287  
   288  	// truncate if too long
   289  	if buf.Len() > maxLen {
   290  		buf.Truncate(maxLen - 3)
   291  		buf.WriteString("...")
   292  	}
   293  
   294  	// replace any invisibles with blanks
   295  	bytes := buf.Bytes()
   296  	for i, b := range bytes {
   297  		switch b {
   298  		case '\t', '\n', '\r':
   299  			bytes[i] = ' '
   300  		}
   301  	}
   302  
   303  	return string(bytes)
   304  }
   305  
   306  func (cmap CommentMap) String() string {
   307  	// print map entries in sorted order
   308  	var nodes []Node
   309  	for node := range cmap {
   310  		nodes = append(nodes, node)
   311  	}
   312  	sort.Sort(byInterval(nodes))
   313  
   314  	var buf bytes.Buffer
   315  	fmt.Fprintln(&buf, "CommentMap {")
   316  	for _, node := range nodes {
   317  		comment := cmap[node]
   318  		// print name of identifiers; print node type for other nodes
   319  		var s string
   320  		if ident, ok := node.(*Ident); ok {
   321  			s = ident.Name
   322  		} else {
   323  			s = fmt.Sprintf("%T", node)
   324  		}
   325  		fmt.Fprintf(&buf, "\t%p  %20s:  %s\n", node, s, summary(comment))
   326  	}
   327  	fmt.Fprintln(&buf, "}")
   328  	return buf.String()
   329  }
   330  

View as plain text