summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/redundantscope.go
blob: 49006019e7d5cd5c3e4080e05c0ead2f48b3ff25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package pkglint

// RedundantScope checks for redundant variable definitions and for variables
// that are accidentally overwritten. It tries to be as correct as possible
// by not flagging anything that is defined conditionally.
//
// There may be some edge cases though like defining PKGNAME, then evaluating
// it using :=, then defining it again. This pattern is so error-prone that
// it should not appear in pkgsrc at all, thus pkglint doesn't even expect it.
// (Well, except for the PKGNAME case, but that's deep in the infrastructure
// and only affects the "nb13" extension.)
//
// TODO: This scope is not only used for detecting redundancies. It also
// provides information about whether the variables are constant or depend on
// other variables. Therefore the name may change soon.
type RedundantScope struct {
	vars        map[string]*redundantScopeVarinfo
	includePath includePath
}
type redundantScopeVarinfo struct {
	vari         *Var
	includePaths []includePath
	lastAction   uint8 // 0 = none, 1 = read, 2 = write
}

func NewRedundantScope() *RedundantScope {
	return &RedundantScope{vars: make(map[string]*redundantScopeVarinfo)}
}

func (s *RedundantScope) Check(mklines *MkLines) {
	mklines.ForEach(func(mkline *MkLine) {
		s.checkLine(mklines, mkline)
	})
}

func (s *RedundantScope) checkLine(mklines *MkLines, mkline *MkLine) {
	s.updateIncludePath(mkline)

	switch {
	case mkline.IsVarassign():
		s.handleVarassign(mkline, mklines.indentation)
	}

	s.handleVarUse(mkline)
}

func (s *RedundantScope) updateIncludePath(mkline *MkLine) {
	if mkline.firstLine == 1 {
		s.includePath.push(mkline.Location.Filename)
	} else {
		s.includePath.popUntil(mkline.Location.Filename)
	}
}

func (s *RedundantScope) handleVarassign(mkline *MkLine, ind *Indentation) {
	varname := mkline.Varname()
	info := s.get(varname)

	defer func() {
		info.vari.Write(mkline, ind.Depth("") > 0, ind.Varnames()...)
		info.lastAction = 2
		s.access(varname)
	}()

	// In the very first assignment, no redundancy can occur.
	prevWrites := info.vari.WriteLocations()
	if len(prevWrites) == 0 {
		return
	}

	// TODO: Just being conditional is only half the truth.
	//  To be precise, the "conditional path" must differ between
	//  this variable assignment and the/any? previous one.
	//  See Test_RedundantScope__overwrite_inside_conditional.
	//  Anyway, too few warnings are better than wrong warnings.
	if info.vari.IsConditional() || ind.Depth("") > 0 {
		return
	}

	// When the variable has been read after the previous write,
	// it is not redundant.
	if info.lastAction == 1 {
		return
	}

	effOp := mkline.Op()
	value := mkline.Value()

	// FIXME: Skip the whole redundancy check if the value is not known to be constant.
	if effOp == opAssign && info.vari.Value() == value {
		effOp = opAssignDefault
	}

	if effOp == opAssignEval && value == mkline.WithoutMakeVariables(value) {
		// Maybe add support for VAR:= ${OTHER} later. This involves evaluating
		// the OTHER variable though using the appropriate scope. Oh, wait,
		// there _is_ a scope here. So if OTHER doesn't refer to further
		// variables it's all possible.
		//
		// TODO: The above idea seems possible and useful.
		effOp = opAssign
	}

	switch effOp {

	case opAssign: // with a different value than before
		if s.includePath.includedByOrEqualsAll(info.includePaths) {

			// The situation is:
			//
			//   including.mk: VAR= initial value
			//   included.mk:  VAR= overwriting     <-- you are here
			//
			// Because the included files is never wrong (by definition),
			// the including file gets the warning in this case.
			s.onOverwrite(prevWrites[len(prevWrites)-1], mkline)
		}

	case opAssignDefault: // or opAssign with the same value as before
		switch {

		case s.includePath.includesOrEqualsAll(info.includePaths):

			// The situation is:
			//
			//   included.mk:  VAR=  value
			//   including.mk: VAR=  value   <-- you are here
			//   including.mk: VAR?= value   <-- or here
			//
			// After including one or more files, the variable is either
			// overwritten or defaulted with the same value as its
			// guaranteed current value. All previous accesses to the
			// variable were either in this file or in an included file.
			s.onRedundant(mkline, prevWrites[len(prevWrites)-1])

		case s.includePath.includedByOrEqualsAll(info.includePaths):

			// The situation is:
			//
			//   including.mk: VAR=  value
			//   included.mk:  VAR?= value   <-- you are here
			//   included.mk:  VAR=  value   <-- or here
			//
			// A variable has been defined in an including file.
			// The current line either has a default assignment or an
			// unconditional assignment. This is common and fine.
			//
			// Except when this line has the same value as the guaranteed
			// current value of the variable. Then it is redundant.
			if info.vari.IsConstant() && info.vari.ConstantValue() == mkline.Value() {
				s.onRedundant(prevWrites[len(prevWrites)-1], mkline)
			}
		}
	}
}

func (s *RedundantScope) handleVarUse(mkline *MkLine) {
	switch {
	case mkline.IsVarassign():
		mkline.ForEachUsed(func(varUse *MkVarUse, time VucTime) {
			varname := varUse.varname
			info := s.get(varname)
			info.vari.Read(mkline)
			info.lastAction = 1
			s.access(varname)
		})

	case mkline.IsDirective():
		// TODO: Handle varuse for conditions and loops.
		break

	case mkline.IsInclude(), mkline.IsSysinclude():
		// TODO: Handle VarUse for includes, which may reference variables.
		break

	case mkline.IsDependency():
		// TODO: Handle VarUse for this case.
	}
}

// access returns the info for the given variable, creating it if necessary.
func (s *RedundantScope) get(varname string) *redundantScopeVarinfo {
	info := s.vars[varname]
	if info == nil {
		v := NewVar(varname)
		info = &redundantScopeVarinfo{v, nil, 0}
		s.vars[varname] = info
	}
	return info
}

// access records the current file location, to be used in later inclusion checks.
func (s *RedundantScope) access(varname string) {
	info := s.vars[varname]
	info.includePaths = append(info.includePaths, s.includePath.copy())
}

func (s *RedundantScope) onRedundant(redundant *MkLine, because *MkLine) {
	if redundant.Op() == opAssignDefault {
		redundant.Notef("Default assignment of %s has no effect because of %s.",
			because.Varname(), redundant.RefTo(because))
	} else {
		redundant.Notef("Definition of %s is redundant because of %s.",
			because.Varname(), redundant.RefTo(because))
	}
}

func (s *RedundantScope) onOverwrite(overwritten *MkLine, by *MkLine) {
	overwritten.Warnf("Variable %s is overwritten in %s.",
		overwritten.Varname(), overwritten.RefTo(by))
	overwritten.Explain(
		"The variable definition in this line does not have an effect since",
		"it is overwritten elsewhere.",
		"This typically happens because of a typo (writing = instead of +=)",
		"or because the line that overwrites",
		"is in another file that is used by several packages.")
}

// includePath remembers the whole sequence of included files,
// such as Makefile includes ../../a/b/buildlink3.mk includes ../../c/d/buildlink3.mk.
//
// This information is used by the RedundantScope to decide whether
// one of two variable assignments is redundant. Two assignments can
// only be redundant if one location includes the other.
type includePath struct {
	files []Path
}

func (p *includePath) push(filename Path) {
	p.files = append(p.files, filename)
}

func (p *includePath) popUntil(filename Path) {
	for p.files[len(p.files)-1] != filename {
		p.files = p.files[:len(p.files)-1]
	}
}

func (p *includePath) includes(other includePath) bool {
	for i, filename := range p.files {
		if i >= len(other.files) || other.files[i] != filename {
			return false
		}
	}
	return len(p.files) < len(other.files)
}

func (p *includePath) includesOrEqualsAll(others []includePath) bool {
	for _, other := range others {
		if !(p.includes(other) || p.equals(other)) {
			return false
		}
	}
	return true
}

func (p *includePath) includedByOrEqualsAll(others []includePath) bool {
	for _, other := range others {
		if !(other.includes(*p) || p.equals(other)) {
			return false
		}
	}
	return true
}

func (p *includePath) equals(other includePath) bool {
	if len(p.files) != len(other.files) {
		return false
	}
	for i, filename := range p.files {
		if other.files[i] != filename {
			return false
		}
	}
	return true
}

func (p *includePath) copy() includePath {
	return includePath{append([]Path(nil), p.files...)}
}