conststrip.go raw

   1  package loader
   2  
   3  // Pre-parse dead constant elimination. Mirrors stage4's stripUnusedConsts in
   4  // ir_typecheck.mx: a package-level single-line const declaration whose name is
   5  // referenced nowhere else in the package is blanked before the parser sees it.
   6  // Generated tables (zerrors, zsysnum) are thousands of unreferenced constants
   7  // and there is no reason to parse or type-check them.
   8  
   9  // collectConstRefs records every identifier in src except the name each
  10  // "const NAME" declaration introduces. The declared name is located by
  11  // position: the identifier at that exact span is the declaration, not a
  12  // reference. The whole source is scanned, not just function bodies, because a
  13  // const used solely by a var initializer or a type declaration is still used.
  14  func collectConstRefs(src []byte, refs map[string]bool) {
  15  	i := 0
  16  	for i < len(src) {
  17  		// The name a single-line "const NAME" declares is not a reference.
  18  		declStart, declEnd := -1, -1
  19  		ls := i
  20  		for ls < len(src) && (src[ls] == ' ' || src[ls] == '\t') {
  21  			ls++
  22  		}
  23  		if ls+6 <= len(src) && src[ls] == 'c' && src[ls+1] == 'o' && src[ls+2] == 'n' && src[ls+3] == 's' && src[ls+4] == 't' && src[ls+5] == ' ' {
  24  			ns := ls + 6
  25  			for ns < len(src) && (src[ns] == ' ' || src[ns] == '\t') {
  26  				ns++
  27  			}
  28  			ne := ns
  29  			for ne < len(src) && isIdentCont(src[ne]) {
  30  				ne++
  31  			}
  32  			if ne > ns {
  33  				declStart, declEnd = ns, ne
  34  			}
  35  		}
  36  		for i < len(src) && src[i] != '\n' {
  37  			if isIdentStart(src[i]) {
  38  				j := i + 1
  39  				for j < len(src) && isIdentCont(src[j]) {
  40  					j++
  41  				}
  42  				if i != declStart || j != declEnd {
  43  					refs[string(src[i:j])] = true
  44  				}
  45  				i = j
  46  				continue
  47  			}
  48  			i++
  49  		}
  50  		if i < len(src) {
  51  			i++
  52  		}
  53  	}
  54  }
  55  
  56  // stripUnusedConsts returns src with every unreferenced, unexported,
  57  // single-line const declaration blanked. Only individual const lines are
  58  // stripped; grouped "const (" blocks are untouched.
  59  func stripUnusedConsts(src []byte, refs map[string]bool) []byte {
  60  	out := make([]byte, 0, len(src))
  61  	i := 0
  62  	for i < len(src) {
  63  		// Look for "const " at line start (after optional whitespace/tab).
  64  		ls := i
  65  		for ls < len(src) && (src[ls] == ' ' || src[ls] == '\t') {
  66  			ls++
  67  		}
  68  		if ls+6 < len(src) && src[ls] == 'c' && src[ls+1] == 'o' && src[ls+2] == 'n' && src[ls+3] == 's' && src[ls+4] == 't' && src[ls+5] == ' ' {
  69  			ns := ls + 6
  70  			for ns < len(src) && (src[ns] == ' ' || src[ns] == '\t') {
  71  				ns++
  72  			}
  73  			ne := ns
  74  			for ne < len(src) && isIdentCont(src[ne]) {
  75  				ne++
  76  			}
  77  			if ne > ns {
  78  				cname := string(src[ns:ne])
  79  				// Exported consts are kept: an importer may use one, e.g.
  80  				// sha256.BlockSize as an array length, and that use is not
  81  				// visible in this package's source.
  82  				exported := cname[0] >= 'A' && cname[0] <= 'Z'
  83  				if !refs[cname] && !exported && constLineIsComplete(src, ls, ne) {
  84  					// Blank the line rather than deleting it. stage4 parses a
  85  					// concatenated package body and maps line numbers back to
  86  					// file:line, so dropping a line moved every later position
  87  					// and a parse error was reported against the wrong file
  88  					// entirely. Keeping the '\n' keeps that mapping and both
  89  					// compilers identical.
  90  					out = append(out, '/', '/')
  91  					for i < len(src) && src[i] != '\n' {
  92  						i++
  93  					}
  94  					if i < len(src) {
  95  						out = append(out, '\n')
  96  						i++
  97  					}
  98  					continue
  99  				}
 100  			}
 101  		}
 102  		for i < len(src) && src[i] != '\n' {
 103  			out = append(out, src[i])
 104  			i++
 105  		}
 106  		if i < len(src) {
 107  			out = append(out, '\n')
 108  			i++
 109  		}
 110  	}
 111  	return out
 112  }
 113  
 114  // constLineIsComplete reports whether a single-line "const NAME = value"
 115  // declaration is wholly contained in its line. The stripper blanks one LINE per
 116  // unreferenced constant, so a declaration whose value continues on the next
 117  // line must be left alone: blanking "const c =" leaves the value behind and the
 118  // parser reports "non-declaration statement outside function body" (x/net/idna
 119  // has 525 such generator-table lines). A line is complete when an '=' follows
 120  // the name and the last significant character can end an expression rather than
 121  // continue one.
 122  func constLineIsComplete(src []byte, lineStart, nameEnd int) bool {
 123  	le := lineStart
 124  	for le < len(src) && src[le] != '\n' {
 125  		le++
 126  	}
 127  	// A trailing line comment is not part of the declaration: x/net/idna's
 128  	// 'const mappings = "" + // Size: 6704 bytes' would otherwise look like it
 129  	// ends in the word "bytes" and a 525-line declaration would be stripped.
 130  	end := le
 131  	inStr := false
 132  	var quote byte
 133  	depth := 0
 134  	for k := lineStart; k+1 < le; k++ {
 135  		c := src[k]
 136  		if inStr {
 137  			if c == '\\' {
 138  				k++
 139  				continue
 140  			}
 141  			if c == quote {
 142  				inStr = false
 143  			}
 144  			continue
 145  		}
 146  		if c == '"' || c == '\'' || c == '`' {
 147  			inStr = true
 148  			quote = c
 149  			continue
 150  		}
 151  		if c == '/' && src[k+1] == '/' {
 152  			end = k
 153  			break
 154  		}
 155  		if c == '(' || c == '[' || c == '{' {
 156  			depth++
 157  		} else if c == ')' || c == ']' || c == '}' {
 158  			if depth > 0 {
 159  				depth--
 160  			}
 161  		}
 162  	}
 163  	// A bracket or string left open at end of line continues on the next line
 164  	// (const x = []T{ / foo( ...); blanking its first line left the rest behind.
 165  	if depth != 0 || inStr {
 166  		return false
 167  	}
 168  	last := end
 169  	for last > nameEnd && (src[last-1] == ' ' || src[last-1] == '\t' || src[last-1] == '\r') {
 170  		last--
 171  	}
 172  	if last <= nameEnd {
 173  		return false
 174  	}
 175  	sawAssign := false
 176  	for k := nameEnd; k < last; k++ {
 177  		if src[k] == '=' {
 178  			sawAssign = true
 179  			break
 180  		}
 181  	}
 182  	if !sawAssign {
 183  		return false
 184  	}
 185  	switch src[last-1] {
 186  	case '=', '+', '-', '*', '/', '%', '|', '&', '^', '<', '>', '(', '[', '{', ',', '.', ':', '!':
 187  		return false
 188  	}
 189  	return true
 190  }
 191  
 192  func isIdentStart(c byte) bool {
 193  	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'
 194  }
 195  
 196  func isIdentCont(c byte) bool {
 197  	return isIdentStart(c) || (c >= '0' && c <= '9')
 198  }
 199