summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/vartypecheck.go
blob: 399c82253f5656f7e0edd5e09cf66d024ce7fad8 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
package pkglint

import (
	"netbsd.org/pkglint/regex"
	"netbsd.org/pkglint/textproc"
	"path"
	"strings"
)

// VartypeCheck groups together the various checks for variables of the different types.
type VartypeCheck struct {
	MkLines *MkLines
	MkLine  *MkLine

	// The name of the variable being checked.
	//
	// In some cases (see WithVarnameValueMatch) it contains not the
	// variable name but more a "description" of a part of a variable.
	// See MachinePlatform for an example.
	Varname    string
	Op         MkOperator
	Value      string
	ValueNoVar string
	MkComment  string // The comment including the "#".
	Guessed    bool   // Whether the type definition is guessed (based on the variable name) or explicitly defined (see vardefs.go).
}

func (cv *VartypeCheck) Errorf(format string, args ...interface{}) { cv.MkLine.Errorf(format, args...) }
func (cv *VartypeCheck) Warnf(format string, args ...interface{})  { cv.MkLine.Warnf(format, args...) }
func (cv *VartypeCheck) Notef(format string, args ...interface{})  { cv.MkLine.Notef(format, args...) }
func (cv *VartypeCheck) Explain(explanation ...string)             { cv.MkLine.Explain(explanation...) }

// Autofix returns the autofix instance belonging to the line.
//
// Usage:
//
//  fix := cv.Autofix()
//
//  fix.Errorf("Must not be ...")
//  fix.Warnf("Should not be ...")
//  fix.Notef("It is also possible ...")
//
//  fix.Explain(
//      "Explanation ...",
//      "... end of explanation.")
//
//  fix.Replace("from", "to")
//  fix.ReplaceAfter("prefix", "from", "to")
//  fix.ReplaceRegex(`[\t ]+`, "space", -1)
//  fix.InsertBefore("new line")
//  fix.InsertAfter("new line")
//  fix.Delete()
//  fix.Custom(func(showAutofix, autofix bool) {})
//
//  fix.Apply()
func (cv *VartypeCheck) Autofix() *Autofix { return cv.MkLine.Autofix() }

// WithValue returns a new VartypeCheck context by copying all
// fields except the value.
//
// This is typically used when calling a related check.
func (cv *VartypeCheck) WithValue(value string) *VartypeCheck {
	return cv.WithVarnameValue(cv.Varname, value)
}

// WithVarnameValue returns a new VartypeCheck context by copying all
// fields except the variable name and the value.
//
// This is typically used when checking parts of composite types.
func (cv *VartypeCheck) WithVarnameValue(varname, value string) *VartypeCheck {
	newVc := *cv
	newVc.Varname = varname
	newVc.Value = value
	newVc.ValueNoVar = cv.MkLine.WithoutMakeVariables(value)
	return &newVc
}

// WithVarnameValueMatch returns a new VartypeCheck context by copying all
// fields except the variable name, the operator (it is set to opUseMatch)
// and the value.
//
// This is typically used when checking parts of composite types,
// such as the patterns from ONLY_FOR_PLATFORM.
func (cv *VartypeCheck) WithVarnameValueMatch(varname, value string) *VartypeCheck {
	newVc := *cv
	newVc.Varname = varname
	newVc.Op = opUseMatch
	newVc.Value = value
	newVc.ValueNoVar = cv.MkLine.WithoutMakeVariables(value)
	return &newVc
}

func (cv *VartypeCheck) AwkCommand() {
	if trace.Tracing {
		trace.Step1("Unchecked AWK command: %q", cv.Value)
	}
}

// BasicRegularExpression checks for a basic regular expression, as
// defined by POSIX.
//
// When they are used in a list variable (as for CHECK_FILES_SKIP), they
// cannot include spaces. Instead, a dot or [[:space:]] must be used.
// The regular expressions do not need any quotation for the shell; all
// quoting issues are handled by the pkgsrc infrastructure.
//
// The opposite situation is when the regular expression is part of a sed
// command. In such a case the shell quoting is undone before checking the
// regular expression, and this is where spaces and tabs can appear.
//
// TODO: Add check for EREs as well.
//
// See https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_03.
// See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03.
func (cv *VartypeCheck) BasicRegularExpression() {

	// same order as in the OpenGroup spec
	allowedAfterBackslash := textproc.NewByteSet(")({}1-9.[\\*^$")

	lexer := textproc.NewLexer(cv.ValueNoVar)

	parseCharacterClass := func() {
		for !lexer.EOF() {
			if lexer.SkipByte('\\') {
				if !lexer.EOF() {
					lexer.Skip(1)
				}
			} else if lexer.SkipByte(']') {
				return
			} else {
				lexer.Skip(1)
			}
		}
	}

	parseBackslash := func() {
		if lexer.EOF() {
			return
		}

		if !lexer.TestByteSet(allowedAfterBackslash) {
			cv.Warnf("In a basic regular expression, a backslash followed by %q is undefined.", lexer.Rest()[:1])
			cv.Explain(
				"Only the characters . [ \\ * ^ $ may be escaped using a backslash.",
				"Except when the escaped character appears in a character class like [\\.a-z].",
				"",
				"To fix this, remove the backslash before the character.")
		}
		lexer.Skip(1)
	}

	for !lexer.EOF() {
		switch {
		case lexer.SkipByte('['):
			parseCharacterClass()

		case lexer.SkipByte('\\'):
			parseBackslash()

		case lexer.Skip(1):
		}
	}
}

func (cv *VartypeCheck) BuildlinkDepmethod() {
	if cv.Value == cv.ValueNoVar && cv.Value != "build" && cv.Value != "full" {
		cv.Warnf("Invalid dependency method %q. Valid methods are \"build\" or \"full\".", cv.Value)
	}
}

func (cv *VartypeCheck) Category() {
	if cv.Value != "wip" && G.Pkgsrc.File(NewPkgsrcPath(NewPath(cv.Value)).JoinNoClean("Makefile")).IsFile() {
		return
	}

	switch cv.Value {
	case
		"chinese",
		"gnome", "gnustep",
		"japanese", "java",
		"kde", "korean",
		"linux", "local",
		"perl5", "plan9", "python",
		"R", "ruby",
		"scm",
		"tcl", "tk",
		"windowmaker",
		"xmms":
	default:
		cv.Errorf("Invalid category %q.", cv.Value)
	}
}

// CFlag is a single option to the C/C++ compiler.
//
// XXX: How can flags like "-D NAME" be handled?
func (cv *VartypeCheck) CFlag() {
	if cv.Op == opUseMatch {
		return
	}

	cflag := cv.Value
	switch {
	case hasPrefix(cflag, "-l"), hasPrefix(cflag, "-L"):
		cv.Warnf("%q is a linker flag and belong to LDFLAGS, LIBS or LDADD instead of %s.",
			cflag, cv.Varname)
	}

	if strings.Count(cflag, "\"")%2 != 0 {
		cv.Warnf("Compiler flag %q has unbalanced double quotes.", cflag)
	}
	if strings.Count(cflag, "'")%2 != 0 {
		cv.Warnf("Compiler flag %q has unbalanced single quotes.", cflag)
	}
}

// Comment checks for the single-line description of a package.
//
// The comment for categories is checked in CheckdirCategory since these
// almost never change.
func (cv *VartypeCheck) Comment() {
	value := cv.Value

	// See pkgtools/url2pkg/files/url2pkg.pl, keyword "COMMENT".
	if value == "TODO: Short description of the package" {
		cv.Errorf("COMMENT must be set.")
	}

	if m, first := match1(value, `^(?i)(a|an)[\t ]`); m {
		cv.Warnf("COMMENT should not begin with %q.", first)
	}

	if G.Pkg != nil && G.Pkg.EffectivePkgbase != "" {
		pkgbase := G.Pkg.EffectivePkgbase
		if hasPrefix(strings.ToLower(value), strings.ToLower(pkgbase+" ")) {
			cv.Warnf("COMMENT should not start with the package name.")
			cv.Explain(
				"The COMMENT is usually displayed together with the package name.",
				"Therefore it does not need to repeat the package name but should",
				"provide additional information instead.")
		}
	}

	if matches(value, `^[a-z]`) && cv.Op == opAssign {
		cv.Warnf("COMMENT should start with a capital letter.")
	}

	if m, isA := match1(value, `\b(is an?)\b`); m {
		cv.Warnf("COMMENT should not contain %q.", isA)
		cv.Explain(
			"The words \"package is a\" are redundant.",
			"Since every package comment could start with them,",
			"it is better to remove this redundancy in all cases.")
	}

	if hasSuffix(value, ".") {
		cv.Warnf("COMMENT should not end with a period.")
	}

	if len(value) > 70 {
		cv.Warnf("COMMENT should not be longer than 70 characters.")
	}

	if hasPrefix(value, "\"") && hasSuffix(value, "\"") ||
		hasPrefix(value, "'") && hasSuffix(value, "'") {
		cv.Warnf("COMMENT should not be enclosed in quotes.")
	}
}

// ConfFiles checks pairs of example file, configuration file.
//
// When a package is installed, the example file is installed as usual
// and is then copied to its final location.
func (cv *VartypeCheck) ConfFiles() {
	words := cv.MkLine.ValueFields(cv.Value)
	if len(words)%2 != 0 {
		cv.Warnf("Values for %s should always be pairs of paths.", cv.Varname)
	}

	for i, word := range words {
		cv.WithValue(word).Pathname()

		if i%2 == 1 && !hasPrefix(word, "${") {
			cv.Warnf("The destination file %q should start with a variable reference.", word)
			cv.Explain(
				"Since pkgsrc can be installed in different locations, the",
				"configuration files will also end up in different locations.",
				"Typical variables that are used for configuration files are",
				"PKG_SYSCONFDIR, PKG_SYSCONFBASE, PREFIX, VARBASE.")
		}
	}
}

func (cv *VartypeCheck) Dependency() {
	value := cv.Value

	parser := NewMkParser(nil, value)
	deppat := parser.Dependency()
	rest := parser.Rest()

	if deppat != nil && deppat.Wildcard == "" && (rest == "{,nb*}" || rest == "{,nb[0-9]*}") {
		cv.Warnf("Dependency patterns of the form pkgbase>=1.0 don't need the \"{,nb*}\" extension.")
		cv.Explain(
			"The \"{,nb*}\" extension is only necessary for dependencies of the",
			"form \"pkgbase-1.2\", since the pattern \"pkgbase-1.2\" doesn't match",
			"the version \"pkgbase-1.2nb5\".",
			"For dependency patterns using the comparison operators,",
			"this is not necessary.")

	} else if deppat == nil && contains(cv.ValueNoVar, "{") {
		// Don't warn about complicated patterns like "{ssh{,6}>=0,openssh>=0}"
		// that pkglint doesn't understand as of January 2019.
		return

	} else if deppat == nil || rest != "" {
		cv.Warnf("Invalid dependency pattern %q.", value)
		cv.Explain(
			"Typical dependencies have the following forms:",
			"",
			"\tpackage>=2.5",
			"\tpackage-[0-9]*",
			"\tpackage-3.141",
			"\tpackage>=2.71828<=3.1415")
		return
	}

	wildcard := deppat.Wildcard
	if m, inside := match1(wildcard, `^\[(.*)\]\*$`); m {
		if inside != "0-9" {
			cv.Warnf("Only [0-9]* is allowed in the numeric part of a dependency.")
			cv.Explain(
				"The pattern -[0-9] means any version.",
				"All other version patterns should be expressed using",
				"the comparison operators like < or >= or even >=2<3.",
				"",
				"Patterns like -[0-7] will only match the first digit of the version",
				"number and will not do the correct thing when the package reaches",
				"version 10.")
		}

	} else if m, ver, suffix := match2(wildcard, `^(\d\w*(?:\.\w+)*)(\.\*|\{,nb\*\}|\{,nb\[0-9\]\*\}|\*|)$`); m {
		if suffix == "" {
			cv.Warnf("Please use %q instead of %q as the version pattern.", ver+"{,nb*}", ver)
			cv.Explain(
				"Without the \"{,nb*}\" suffix, this version pattern only matches",
				"package versions that don't have a PKGREVISION (which is the part",
				"after the \"nb\").")
		}
		if suffix == "*" {
			cv.Warnf("Please use %q instead of %q as the version pattern.", ver+".*", ver+"*")
			cv.Explain(
				"For example, the version \"1*\" also matches \"10.0.0\", which is",
				"probably not intended.")
		}

	} else if wildcard == "*" {
		cv.Warnf("Please use \"%[1]s-[0-9]*\" instead of \"%[1]s-*\".", deppat.Pkgbase)
		cv.Explain(
			"If you use a * alone, the package specification may match other",
			"packages that have the same prefix but a longer name.",
			"For example, foo-* matches foo-1.2 but also",
			"foo-client-1.2 and foo-server-1.2.")
	}

	withoutCharClasses := replaceAll(wildcard, `\[[\d-]+\]`, "")
	if contains(withoutCharClasses, "-") {
		cv.Warnf("The version pattern %q should not contain a hyphen.", wildcard)
		cv.Explain(
			"Pkgsrc interprets package names with version numbers like this:",
			"",
			"\t\"foo-2.0-2.1.x\" => pkgbase \"foo\", version \"2.0-2.1.x\"",
			"",
			"To make the \"2.0\" above part of the package basename, the hyphen",
			"must be omitted, so the full package name becomes \"foo2.0-2.1.x\".")
	}
}

func (cv *VartypeCheck) DependencyWithPath() {
	value := cv.Value
	valueNoVar := cv.ValueNoVar

	if valueNoVar == "" || valueNoVar == ":" {
		return
	}

	parts := cv.MkLine.ValueSplit(value, ":")
	if len(parts) == 2 {
		pattern := parts[0]
		relpath := NewRelPathString(parts[1])
		pathParts := relpath.Parts()
		pkg := pathParts[len(pathParts)-1]

		if len(pathParts) >= 2 && pathParts[0] == ".." && pathParts[1] != ".." {
			cv.Warnf("Dependency paths should have the form \"../../category/package\".")
			cv.MkLine.ExplainRelativeDirs()
		}

		if !containsVarRef(relpath.String()) {
			MkLineChecker{cv.MkLines, cv.MkLine}.CheckRelativePkgdir(relpath)
		}

		switch pkg {
		case "gettext":
			cv.Warnf("Please use USE_TOOLS+=msgfmt instead of this dependency.")
		case "perl5":
			cv.Warnf("Please use USE_TOOLS+=perl:run instead of this dependency.")
		case "gmake":
			cv.Warnf("Please use USE_TOOLS+=gmake instead of this dependency.")
		}

		cv.WithValue(pattern).Dependency()

		return
	}

	cv.Warnf("Invalid dependency pattern with path %q.", value)
	cv.Explain(
		"Examples for valid dependency patterns with path are:",
		"  package-[0-9]*:../../category/package",
		"  package>=3.41:../../category/package",
		"  package-2.718{,nb*}:../../category/package")
}

func (cv *VartypeCheck) DistSuffix() {
	if cv.Value == ".tar.gz" && !hasPrefix(cv.MkComment, "#") {
		cv.Notef("%s is \".tar.gz\" by default, so this definition may be redundant.", cv.Varname)
		cv.Explain(
			"To check whether the definition is really redundant:",
			"",
			sprintf("\t1. run %q", bmake("show-var VARNAME="+cv.Varname)),
			"\t2. remove this definition",
			sprintf("\t3. run %q again", bmake("show-var VARNAME="+cv.Varname)),
			"",
			"If the values from step 1 and step 3 really differ, add a comment to this line",
			"in the Makefile that this (apparently redundant) definition is really needed.")
	}
}

func (cv *VartypeCheck) EmulPlatform() {
	const rePart = `(?:\[[^\]]+\]|[^-\[])+`
	const rePair = `^(` + rePart + `)-(` + rePart + `)$`
	if m, opsysPattern, archPattern := match2(cv.Value, rePair); m {
		opsysCv := cv.WithVarnameValue("the operating system part of "+cv.Varname, opsysPattern)
		BtEmulOpsys.checker(opsysCv)

		archCv := cv.WithVarnameValue("the hardware architecture part of "+cv.Varname, archPattern)
		BtEmulArch.checker(archCv)
	} else {
		cv.Warnf("%q is not a valid emulation platform.", cv.Value)
		cv.Explain(
			"An emulation platform has the form <OPSYS>-<MACHINE_ARCH>.",
			"OPSYS is the lower-case name of the operating system, and",
			"MACHINE_ARCH is the hardware architecture.",
			"",
			"Examples:",
			"* linux-i386",
			"* irix-mipsel")
	}
}

// Enum checks an enumeration for valid values.
//
// The given allowedValues contains all allowed enum values.
// The given basicType is only provided to lazily access the allowed enum values as a sorted list.
func (cv *VartypeCheck) Enum(allowedValues map[string]bool, basicType *BasicType) {
	if cv.Op == opUseMatch {
		if !allowedValues[cv.Value] && cv.Value == cv.ValueNoVar {
			canMatch := false
			for value := range allowedValues {
				if ok, err := path.Match(cv.Value, value); err != nil {
					cv.Warnf("Invalid match pattern %q.", cv.Value)
					return
				} else if ok {
					canMatch = true
				}
			}
			if !canMatch {
				cv.Warnf("The pattern %q cannot match any of { %s } for %s.",
					cv.Value, basicType.AllowedEnums(), cv.Varname)
			}
		}
		return
	}

	if cv.Value == cv.ValueNoVar && !allowedValues[cv.Value] {
		cv.Warnf("%q is not valid for %s. Use one of { %s } instead.",
			cv.Value, cv.Varname, basicType.AllowedEnums())
	}
}

func (cv *VartypeCheck) FetchURL() {
	fetchURL := cv.Value
	url := strings.TrimPrefix(fetchURL, "-")
	hyphen := condStr(len(fetchURL) > len(url), "-", "")
	hyphenSubst := condStr(hyphen != "", ":S,^,-,", "")

	cv.WithValue(url).URL()

	trimURL := url[len(url)-len(replaceAll(url, `^\w+://`, "")):]
	protoLen := len(url) - len(trimURL)

	for trimSiteURL, siteName := range G.Pkgsrc.MasterSiteURLToVar {
		if !hasPrefix(trimURL, trimSiteURL) {
			continue
		}

		subdir := trimURL[len(trimSiteURL):]
		if hasPrefix(trimURL, "github.com/") {
			subdir = strings.SplitAfter(subdir, "/")[0]
			commonPrefix := hyphen + url[:protoLen+len(trimSiteURL)+len(subdir)]
			cv.Warnf("Please use ${%s%s:=%s} instead of %q and run %q for further instructions.",
				siteName, hyphenSubst, subdir, commonPrefix, bmakeHelp("github"))
		} else {
			cv.Warnf("Please use ${%s%s:=%s} instead of %q.", siteName, hyphenSubst, subdir, hyphen+url)
		}
		return
	}

	tokens := cv.MkLine.Tokenize(url, false)
	for _, token := range tokens {
		varUse := token.Varuse
		if varUse == nil {
			continue
		}

		name := varUse.varname
		if !hasPrefix(name, "MASTER_SITE_") {
			continue
		}

		if G.Pkgsrc.MasterSiteVarToURL[name] == "" {
			if G.Pkg == nil || !G.Pkg.vars.IsDefined(name) {
				cv.Errorf("The site %s does not exist.", name)
			}
		}

		if len(varUse.modifiers) != 1 || !hasPrefix(varUse.modifiers[0].Text, "=") {
			continue
		}

		subdir := varUse.modifiers[0].Text[1:]
		if !hasSuffix(subdir, "/") {
			cv.Errorf("The subdirectory in %s must end with a slash.", name)
		}
	}

	switch {
	case cv.Op == opUseMatch,
		hasSuffix(fetchURL, "/"),
		hasSuffix(fetchURL, "="),
		hasSuffix(fetchURL, ":"),
		hasPrefix(fetchURL, "-"),
		tokens[len(tokens)-1].Varuse != nil:
		break

	default:
		cv.Warnf("The fetch URL %q should end with a slash.", fetchURL)
		cv.Explain(
			"The filename from DISTFILES is appended directly to this base URL.",
			"Therefore it should typically end with a slash, or sometimes with",
			"an equals sign or a colon.",
			"",
			"To specify a full URL directly, prefix it with a hyphen, such as in",
			"-https://example.org/distfile-1.0.tar.gz.")
	}
}

// Filename checks that filenames use only limited special characters.
//
// See http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap03.html#tag_03_169
func (cv *VartypeCheck) Filename() {
	valid := regex.Pattern(condStr(
		cv.Op == opUseMatch,
		`[%*+,\-.0-9?@A-Z\[\]_a-z~]`,
		`[%+,\-.0-9@A-Z_a-z~]`))

	invalid := replaceAll(cv.ValueNoVar, valid, "")
	if invalid == "" {
		return
	}

	cv.Warnf(
		condStr(cv.Op == opUseMatch,
			"The filename pattern %q contains the invalid character%s %q.",
			"The filename %q contains the invalid character%s %q."),
		cv.Value,
		condStr(len(invalid) > 1, "s", ""),
		invalid)
}

func (cv *VartypeCheck) FilePattern() {

	// TODO: Decide whether to call this a "mask" or a "pattern", and use only that word everywhere.

	invalid := replaceAll(cv.ValueNoVar, `[%*+,\-.0-9?@A-Z\[\]_a-z~]`, "")
	if invalid == "" {
		return
	}

	cv.Warnf("The filename pattern %q contains the invalid character%s %q.",
		cv.Value,
		condStr(len(invalid) > 1, "s", ""),
		invalid)
}

func (cv *VartypeCheck) FileMode() {
	switch {
	case cv.Value != "" && cv.ValueNoVar == "":
		// Fine.
	case matches(cv.Value, `^[0-7]{3,4}$`):
		// Fine.
	default:
		cv.Warnf("Invalid file mode %q.", cv.Value)
	}
}

func (cv *VartypeCheck) GccReqd() {
	cv.Version()

	if m, major := match1(cv.Value, `^([5-9])\.\d+$`); m {
		fix := cv.Autofix()

		fix.Warnf("GCC version numbers should only contain the major version (%s).", major)
		fix.Explain(
			"For GCC up to 4.x, the major version consists of the first and",
			"second number, such as 4.8.",
			"",
			"Starting with GCC >= 5, the major version is only the first number",
			"such as 5 or 7.")
		fix.Replace(cv.Value, major)
		fix.Apply()
	}
}

func (cv *VartypeCheck) Homepage() {
	cv.URL()

	m, wrong, sitename, subdir := match3(cv.Value, `^(\$\{(MASTER_SITE\w+)(?::=([\w\-/]+))?\})`)
	if !m {
		return
	}

	baseURL := G.Pkgsrc.MasterSiteVarToURL[sitename]
	if sitename == "MASTER_SITES" && G.Pkg != nil {
		mkline := G.Pkg.vars.FirstDefinition("MASTER_SITES")
		if mkline != nil {
			if !containsVarRef(mkline.Value()) {
				masterSites := cv.MkLine.ValueFields(mkline.Value())
				if len(masterSites) > 0 {
					baseURL = masterSites[0]
				}
			}
		}
	}

	fixedURL := baseURL + subdir

	fix := cv.Autofix()
	if baseURL != "" {
		fix.Warnf("HOMEPAGE should not be defined in terms of MASTER_SITEs. Use %s directly.", fixedURL)
	} else {
		fix.Warnf("HOMEPAGE should not be defined in terms of MASTER_SITEs.")
	}
	fix.Explain(
		"The HOMEPAGE is a single URL, while MASTER_SITES is a list of URLs.",
		"As long as this list has exactly one element, this works, but as",
		"soon as another site is added, the HOMEPAGE would not be a valid",
		"URL anymore.",
		"",
		"Defining MASTER_SITES=${HOMEPAGE} is ok, though.")
	if baseURL != "" {
		fix.Replace(wrong, fixedURL)
	}
	fix.Apply()
}

// Identifier checks for valid identifiers in various contexts, limiting the
// valid characters to A-Za-z0-9_.
func (cv *VartypeCheck) IdentifierDirect() {
	if cv.Op == opUseMatch {
		if cv.Value == cv.ValueNoVar && !matches(cv.Value, `^[\w*\-?\[\]]+$`) {
			cv.Warnf("Invalid identifier pattern %q for %s.", cv.Value, cv.Varname)
		}
		return
	}

	if cv.Value != cv.ValueNoVar {
		cv.Errorf("Identifiers for %s must not refer to other variables.", cv.Varname)
		return
	}

	switch {
	case matches(cv.ValueNoVar, `^[+\-.\w]+$`):
		// Fine.

	case cv.Value != "" && cv.ValueNoVar == "":
		// Don't warn here.

	default:
		cv.Warnf("Invalid identifier %q.", cv.Value)
	}
}

// Identifier checks for valid identifiers in various contexts, limiting the
// valid characters to A-Za-z0-9_.
func (cv *VartypeCheck) IdentifierIndirect() {
	if cv.Value == cv.ValueNoVar {
		cv.IdentifierDirect()
	}
}

func (cv *VartypeCheck) Integer() {
	if !matches(cv.Value, `^\d+$`) {
		cv.Warnf("Invalid integer %q.", cv.Value)
	}
}

func (cv *VartypeCheck) LdFlag() {
	if cv.Op == opUseMatch {
		return
	}

	ldflag := cv.Value
	if m, rpathFlag := match1(ldflag, `^(-Wl,(?:-R|-rpath|--rpath))`); m {
		cv.Warnf("Please use \"${COMPILER_RPATH_FLAG}\" instead of %q.", rpathFlag)
		return
	}

	switch {
	case ldflag == "-P",
		ldflag == "-E",
		hasPrefix(ldflag, "-D"),
		hasPrefix(ldflag, "-U"),
		hasPrefix(ldflag, "-I"):
		cv.Warnf("%q is a compiler flag and belongs on CFLAGS, CPPFLAGS, CXXFLAGS or FFLAGS instead of %s.", cv.Value, cv.Varname)
	}
}

func (cv *VartypeCheck) License() {
	(&LicenseChecker{cv.MkLines, cv.MkLine}).Check(cv.Value, cv.Op)
}

func (cv *VartypeCheck) MachineGnuPlatform() {
	if cv.Value != cv.ValueNoVar {
		return
	}

	const rePart = `(?:\[[^\]]+\]|[^-\[])+`
	const rePair = `^(` + rePart + `)-(` + rePart + `)$`
	const reTriple = `^(` + rePart + `)-(` + rePart + `)-(` + rePart + `)$`

	pattern := cv.Value
	if matches(pattern, rePair) && hasSuffix(pattern, "*") {
		pattern += "-*"
	}

	if m, archPattern, vendorPattern, opsysPattern := match3(pattern, reTriple); m {
		archCv := cv.WithVarnameValueMatch(
			"the hardware architecture part of "+cv.Varname,
			archPattern)
		BtMachineGnuArch.checker(archCv)

		_ = vendorPattern

		opsysCv := cv.WithVarnameValueMatch(
			"the operating system part of "+cv.Varname,
			opsysPattern)
		BtMachineGnuPlatformOpsys.checker(opsysCv)

	} else {
		cv.Warnf("%q is not a valid platform pattern.", cv.Value)
		cv.Explain(
			"A platform pattern has the form <OPSYS>-<OS_VERSION>-<MACHINE_ARCH>.",
			"Each of these components may use wildcards.",
			"",
			"Examples:",
			"* NetBSD-[456].*-i386",
			"* *-*-*",
			"* Linux-*-*")
	}
}

func (cv *VartypeCheck) MachinePlatform() {
	cv.MachinePlatformPattern()
}

func (cv *VartypeCheck) MachinePlatformPattern() {
	if cv.Value != cv.ValueNoVar {
		return
	}

	const rePart = `(?:\[[^\]]+\]|[^-\[])+`
	const rePair = `^(` + rePart + `)-(` + rePart + `)$`
	const reTriple = `^(` + rePart + `)-(` + rePart + `)-(` + rePart + `)$`

	pattern := cv.Value
	if matches(pattern, rePair) && hasSuffix(pattern, "*") {
		pattern += "-*"
	}

	if m, opsysPattern, versionPattern, archPattern := match3(pattern, reTriple); m {
		opsysCv := cv.WithVarnameValueMatch("the operating system part of "+cv.Varname, opsysPattern)
		BtMachineOpsys.checker(opsysCv)

		versionCv := cv.WithVarnameValueMatch("the version part of "+cv.Varname, versionPattern)
		versionCv.Version()

		archCv := cv.WithVarnameValueMatch("the hardware architecture part of "+cv.Varname, archPattern)
		BtMachineArch.checker(archCv)

	} else {
		cv.Warnf("%q is not a valid platform pattern.", cv.Value)
		cv.Explain(
			"A platform pattern has the form <OPSYS>-<OS_VERSION>-<MACHINE_ARCH>.",
			"Each of these components may be a shell globbing expression.",
			"",
			"Examples:",
			"* NetBSD-[456].*-i386",
			"* *-*-*",
			"* Linux-*-*")
	}
}

func (cv *VartypeCheck) MailAddress() {
	value := cv.Value

	m, _, domain := match2(value, `^([+\-.0-9A-Z_a-z]+)@([-\w\d.]+)$`)
	if !m {
		cv.Warnf("\"%s\" is not a valid mail address.", value)
		return
	}

	if strings.EqualFold(domain, "NetBSD.org") && domain != "NetBSD.org" {
		cv.Warnf("Please write \"NetBSD.org\" instead of %q.", domain)
	}

	if matches(value, `(?i)^(tech-pkg|packages)@NetBSD\.org$`) {
		cv.Errorf("This mailing list address is obsolete. Use pkgsrc-users@NetBSD.org instead.")
	}
}

// Message is a plain string. When defining a message variable, it should
// not be enclosed in quotes since that is the job of the code that uses
// the message.
//
// Lists of messages use a different type since they need the quotes
// around each message; see PKG_FAIL_REASON.
func (cv *VartypeCheck) Message() {
	varname, value := cv.Varname, cv.Value

	if matches(value, `^[\"'].*[\"']$`) {
		cv.Warnf("%s should not be quoted.", varname)
		cv.Explain(
			"The quoting is only needed for variables which are interpreted as",
			"multiple words (or, generally speaking, a list of something).",
			"A single text message does not belong to this class,",
			"since it is only printed as a whole.")
	}
}

// Option checks whether a single package option from options.mk conforms to the naming conventions.
func (cv *VartypeCheck) Option() {
	value := cv.Value

	if value != cv.ValueNoVar {
		return
	}

	validName := regex.Pattern(`^-?([a-z][-0-9a-z_+]*)$`)
	if cv.Op == opUseMatch {
		validName = `^-?([a-z][*+\-0-9?\[\]_a-z]*)$`
	}

	// TODO: Distinguish between:
	//  - a bare option name (must start with a letter),
	//  - an option selection (may have a leading hyphen).
	m, optname := match1(value, validName)
	if !m {
		cv.Errorf("Invalid option name %q. Option names must start with a lowercase letter and be all-lowercase.", value)
		return
	}

	if !cv.MkLines.once.FirstTimeSlice("option:", optname) {
		return
	}

	if contains(optname, "_") {
		cv.Warnf("Use of the underscore character in option names is deprecated.")
		return
	}

	if !strings.ContainsAny(optname, "*?[") {
		if _, found := G.Pkgsrc.PkgOptions[optname]; !found {
			cv.Warnf("Unknown option %q.", optname)
			cv.Explain(
				"This option is not documented in the mk/defaults/options.description file.",
				"Please think of a brief but precise description and either",
				"update that file yourself or suggest a description for this option",
				"on the tech-pkg@NetBSD.org mailing list.")
		}
	}
}

// Pathlist checks variables like the PATH environment variable.
func (cv *VartypeCheck) Pathlist() {
	value := cv.Value

	// Sometimes, variables called PATH contain a single pathname,
	// especially those with auto-guessed type from MkLine.VariableType.
	if !contains(value, ":") && cv.Guessed {
		cv.Pathname()
		return
	}

	for _, dir := range cv.MkLine.ValueSplit(value, ":") {

		dirNoVar := cv.MkLine.WithoutMakeVariables(dir)
		if !matches(dirNoVar, `^[-0-9A-Za-z._~+%/]*$`) {
			cv.Warnf("%q is not a valid pathname.", dir)
		}

		if !hasPrefix(dir, "/") && !hasPrefix(dir, "${") {
			cv.Errorf("The component %q of %s must be an absolute path.", dir, cv.Varname)
			cv.Explain(
				"Relative paths in the PATH variable are a security risk.",
				"They also make the execution unreliable since they are",
				"evaluated relative to the current directory of the process,",
				"which means that after a \"cd\", different commands might be run.")
		}
	}
}

// PathPattern is a shell pattern for pathnames, possibly including slashes.
//
// See FilePattern.
func (cv *VartypeCheck) PathPattern() {
	invalid := replaceAll(cv.ValueNoVar, `[%*+,\-./0-9?@A-Z\[\]_a-z~]`, "")
	if invalid == "" {
		return
	}

	cv.Warnf("The pathname pattern %q contains the invalid character%s %q.",
		cv.Value,
		condStr(len(invalid) > 1, "s", ""),
		invalid)
}

// Pathname checks for pathnames.
//
// Like Filename, but including slashes.
//
// See http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap03.html#tag_03_266
func (cv *VartypeCheck) Pathname() {
	valid := regex.Pattern(condStr(
		cv.Op == opUseMatch,
		`[%*+,\-./0-9?@A-Z\[\]_a-z~]`,
		`[%+,\-./0-9@A-Z_a-z~]`))
	invalid := replaceAll(cv.ValueNoVar, valid, "")
	if invalid == "" {
		return
	}

	cv.Warnf(
		condStr(cv.Op == opUseMatch,
			"The pathname pattern %q contains the invalid character%s %q.",
			"The pathname %q contains the invalid character%s %q."),
		cv.Value,
		condStr(len(invalid) > 1, "s", ""),
		invalid)
}

func (cv *VartypeCheck) Perl5Packlist() {
	if cv.Value != cv.ValueNoVar {
		cv.Warnf("%s should not depend on other variables.", cv.Varname)
	}
}

func (cv *VartypeCheck) Perms() {
	if cv.Value == "${ROOT_USER}" || cv.Value == "${ROOT_GROUP}" {
		valueName := cv.Value[2 : len(cv.Value)-1]
		fix := cv.Autofix()
		fix.Errorf("%s must not be used in permission definitions. Use REAL_%[1]s instead.", valueName)
		fix.Replace(valueName, "REAL_"+valueName)
		fix.Apply()
	}
}

func (cv *VartypeCheck) Pkgname() {
	value := cv.Value

	if cv.Op != opUseMatch && value == cv.ValueNoVar && !matches(value, rePkgname) {
		cv.Warnf("%q is not a valid package name.", value)
		cv.Explain(
			"A valid package name has the form packagename-version, where version",
			"consists only of digits, letters and dots.")
	}

	if matches(value, `nb\d+$`) {
		cv.Errorf("The \"nb\" part of the version number belongs in PKGREVISION.")
	}
}

func (cv *VartypeCheck) PkgOptionsVar() {
	cv.VariableName()

	// TODO: Replace regex with proper VarUse.
	if matches(cv.Value, `\$\{PKGBASE[:\}]`) {
		cv.Errorf("PKGBASE must not be used in PKG_OPTIONS_VAR.")
		cv.Explain(
			"PKGBASE is defined in bsd.pkg.mk, which is included as the",
			"very last file, but PKG_OPTIONS_VAR is evaluated earlier.",
			"Use ${PKGNAME:C/-[0-9].*//} instead.")
	}

	// PR 46570, item "6. It should complain in PKG_OPTIONS_VAR is wrong"
	if !hasPrefix(cv.Value, "PKG_OPTIONS.") {
		cv.Errorf("PKG_OPTIONS_VAR must be of the form %q, not %q.", "PKG_OPTIONS.*", cv.Value)
	}
}

// Pkgpath checks a directory name relative to the top-level pkgsrc directory.
//
// Despite its name, it is more similar to RelativePkgDir than to RelativePkgPath.
func (cv *VartypeCheck) Pkgpath() {
	cv.Pathname()

	value := cv.Value
	if value != cv.ValueNoVar || cv.Op == opUseMatch {
		return
	}

	pkgpath := NewPkgsrcPath(NewPath(value))
	if !G.Wip && pkgpath.HasPrefixPath("wip") {
		cv.Errorf("A main pkgsrc package must not depend on a pkgsrc-wip package.")
	}

	pkgdir := G.Pkgsrc.File(pkgpath)
	if !pkgdir.JoinNoClean("Makefile").IsFile() {
		cv.Errorf("There is no package in %q.",
			cv.MkLine.Rel(pkgdir))
		return
	}

	if !matches(value, `^([^./][^/]*/[^./][^/]*)$`) {
		cv.Errorf("%q is not a valid path to a package.", pkgpath.String())
		cv.Explain(
			"A path to a package has the form \"category/pkgbase\".",
			"It is relative to the pkgsrc root.")
	}
}

func (cv *VartypeCheck) Pkgrevision() {
	if !matches(cv.Value, `^[1-9]\d*$`) {
		cv.Errorf("%s must be a positive integer number.", cv.Varname)
	}
	if cv.MkLine.Basename != "Makefile" {
		cv.Errorf("%s only makes sense directly in the package Makefile.", cv.Varname)
		cv.Explain(
			"Usually, different packages using the same Makefile.common have",
			"different dependencies and will be bumped at different times (e.g.",
			"for shlib major bumps) and thus the PKGREVISIONs must be in the",
			"separate Makefiles.",
			"There is no practical way of having this information in a commonly used Makefile.")
	}
}

// PrefixPathname checks for a pathname relative to ${PREFIX}.
func (cv *VartypeCheck) PrefixPathname() {
	if NewPath(cv.Value).IsAbs() {
		cv.Errorf("The pathname %q in %s must be relative to ${PREFIX}.",
			cv.Value, cv.Varname)
		return
	}

	if m, manSubdir := match1(cv.Value, `^man/(.+)`); m {
		from := "${PKGMANDIR}/" + manSubdir
		fix := cv.Autofix()
		fix.Warnf("Please use %q instead of %q.", from, cv.Value)
		fix.Replace(cv.Value, from)
		fix.Apply()
	}
}

func (cv *VartypeCheck) PythonDependency() {
	if cv.Value != cv.ValueNoVar {
		cv.Warnf("Python dependencies should not contain variables.")
	} else if !matches(cv.ValueNoVar, `^[+\-.0-9A-Z_a-z]+(?:|:link|:build)$`) {
		cv.Warnf("Invalid Python dependency %q.", cv.Value)
		cv.Explain(
			"Python dependencies must be an identifier for a package, as",
			"specified in lang/python/versioned_dependencies.mk.",
			"This identifier may be followed by :build for a build-time only",
			"dependency, or by :link for a run-time only dependency.")
	}
}

func (cv *VartypeCheck) RPkgName() {
	if cv.Op == opUseMatch {
		return
	}

	if cv.Value != cv.ValueNoVar {
		cv.Warnf("The R package name should not contain variables.")
		return
	}

	if hasPrefix(cv.Value, "R-") {
		cv.Warnf("The %s does not need the %q prefix.", cv.Varname, "R-")
	}

	invalid := replaceAll(cv.Value, `[\w\-.+]`, "")
	if invalid != "" {
		cv.Warnf("The R package name contains the invalid characters %q.", invalid)
	}
}

func (cv *VartypeCheck) RPkgVer() {
	value := cv.Value
	if cv.Op != opUseMatch && value == cv.ValueNoVar && !matches(value, `^\d[\w-.]*$`) {
		cv.Warnf("Invalid R version number %q.", value)
	}
}

// RelativePkgDir refers to a package directory, e.g. ../../category/pkgbase.
func (cv *VartypeCheck) RelativePkgDir() {
	if NewPath(cv.Value).IsAbs() {
		cv.Errorf("The path %q must be relative.", cv.Value)
		return
	}

	MkLineChecker{cv.MkLines, cv.MkLine}.CheckRelativePkgdir(NewRelPathString(cv.Value))
}

// RelativePkgPath refers to a file or directory, e.g. ../../category/pkgbase,
// ../../category/pkgbase/Makefile.
//
// See RelativePkgDir, which requires a directory, not a file.
func (cv *VartypeCheck) RelativePkgPath() {
	if NewPath(cv.Value).IsAbs() {
		cv.Errorf("The path %q must be relative.", cv.Value)
		return
	}

	MkLineChecker{cv.MkLines, cv.MkLine}.CheckRelativePath(NewRelPathString(cv.Value), true)
}

func (cv *VartypeCheck) Restricted() {
	if cv.Value != "${RESTRICTED}" {
		cv.Warnf("The only valid value for %s is ${RESTRICTED}.", cv.Varname)
		cv.Explain(
			"These variables are used to control which files may be mirrored on",
			"FTP servers or CD-ROM collections.",
			"They are not intended to mark",
			"packages whose only MASTER_SITES are on ftp.NetBSD.org.")
	}
}

func (cv *VartypeCheck) SedCommands() {
	tokens, rest := splitIntoShellTokens(cv.MkLine.Line, cv.Value)
	if rest != "" {
		if contains(cv.MkLine.Text, "#") {
			cv.Errorf("Invalid shell words %q in sed commands.", rest)
			cv.Explain(
				"When sed commands have embedded \"#\" characters, they need to be",
				"escaped with a backslash, otherwise make(1) will interpret them as a",
				"comment, even if they occur in single or double quotes or whatever.")
		}
		return
	}

	ntokens := len(tokens)
	ncommands := 0
	extended := false

	checkSedCommand := func(quotedCommand string) {
		// TODO: Remember the extended flag for the whole file, especially
		//  for SUBST_SED.* variables.
		if !extended {
			command := cv.MkLine.UnquoteShell(quotedCommand, true)
			if !hasPrefix(command, "s") {
				return
			}

			// The :C modifier is similar enough for parsing.
			ok, _, from, _, _ := MkVarUseModifier{"C" + command[1:]}.MatchSubst()
			if !ok {
				return
			}

			cv.WithValue(from).BasicRegularExpression()
		}
	}

	for i := 0; i < ntokens; i++ {
		token := tokens[i]

		switch {
		case token == "-e":
			if i+1 >= ntokens {
				cv.Errorf("The -e option to sed requires an argument.")
				break
			}

			// Check the real sed command here.
			i++
			ncommands++
			if ncommands > 1 {
				cv.Warnf("Each sed command should appear in an assignment of its own.")
				cv.Explain(
					"For example, instead of",
					"    SUBST_SED.foo+=        -e s,command1,, -e s,command2,,",
					"use",
					"    SUBST_SED.foo+=        -e s,command1,,",
					"    SUBST_SED.foo+=        -e s,command2,,",
					"",
					"This way, short sed commands cannot be hidden at the end of a line.")
			}

			checkSedCommand(tokens[i])

		case token == "-E":
			// Switch to extended regular expressions mode.
			extended = true

		case token == "-n":
			// Don't print lines per default.

		case matches(token, `^["']?(\d+|/.*/)?s`):
			// TODO: "prefix with" instead of "use".
			cv.Notef("Please always use \"-e\" in sed commands, even if there is only one substitution.")
			checkSedCommand(token)

		default:
			cv.Warnf("Unknown sed command %q.", token)
		}
	}
}

func (cv *VartypeCheck) ShellCommand() {
	if cv.Op == opUseMatch || cv.Op == opUseCompare || cv.Op == opAssignAppend {
		return
	}
	setE := true
	ck := NewShellLineChecker(cv.MkLines, cv.MkLine)
	ck.checkVarUse = false
	ck.CheckShellCommand(cv.Value, &setE, RunTime)
}

// ShellCommands checks for zero or more shell commands, each terminated with a semicolon.
func (cv *VartypeCheck) ShellCommands() {
	ck := NewShellLineChecker(cv.MkLines, cv.MkLine)
	ck.checkVarUse = false
	ck.CheckShellCommands(cv.Value, RunTime)
}

func (cv *VartypeCheck) ShellWord() {
	ck := NewShellLineChecker(cv.MkLines, cv.MkLine)
	ck.checkVarUse = false
	ck.CheckWord(cv.Value, true, RunTime)
}

func (cv *VartypeCheck) Stage() {
	if !matches(cv.Value, `^(?:pre|do|post)-(?:extract|patch|configure|build|test|install)`) {
		cv.Warnf("Invalid stage name %q. Use one of {pre,do,post}-{extract,patch,configure,build,test,install}.", cv.Value)
	}
}

// Tool checks for tool names like "awk", "m4:pkgsrc", "digest:bootstrap".
//
// TODO: Distinguish between Tool and ToolDependency.
func (cv *VartypeCheck) Tool() {
	if cv.Varname == "TOOLS_NOOP" && cv.Op == opAssignAppend {
		// no warning for package-defined tool definitions

	} else if m, toolname, tooldep := match2(cv.Value, `^([-\w]+|\[)(?::(\w+))?$`); m {
		if tool, _ := G.Tool(cv.MkLines, toolname, RunTime); tool == nil {
			cv.Errorf("Unknown tool %q.", toolname)
		}

		switch tooldep {
		case "", "bootstrap", "build", "pkgsrc", "run", "test":
		default:
			cv.Errorf("Invalid tool dependency %q. Use one of \"bootstrap\", \"build\", \"pkgsrc\", \"run\" or \"test\".", tooldep)
		}

	} else if cv.Op != opUseMatch && cv.Value == cv.ValueNoVar {
		cv.Errorf("Invalid tool dependency %q.", cv.Value)
		cv.Explain(
			"A tool dependency typically looks like \"sed\" or \"sed:run\".")
	}
}

// Unknown doesn't check for anything.
//
// Used for:
//  - infrastructure variables that are not in vardefs.go
//  - other variables whose type is unknown or uninteresting enough to
//    warrant the creation of a specialized type
func (cv *VartypeCheck) Unknown() {
	// Do nothing.
}

func (cv *VartypeCheck) URL() {
	value := cv.Value

	if value == "" && hasPrefix(cv.MkComment, "#") {
		// Ok

	} else if containsVarRef(value) {
		// No further checks

	} else if m, _, host, _, _ := match4(value, `^(https?|ftp|gopher)://([-0-9A-Za-z.]+)(?::(\d+))?/([-%&+,./0-9:;=?@A-Z_a-z~]|#)*$`); m {
		if matches(host, `(?i)\.NetBSD\.org$`) && !matches(host, `\.NetBSD\.org$`) {
			fix := cv.Autofix()
			fix.Warnf("Please write NetBSD.org instead of %s.", host)
			fix.ReplaceRegex(`(?i)NetBSD\.org`, "NetBSD.org", 1)
			fix.Apply()
		}

	} else if m, scheme, _, absPath := match3(value, `^([0-9A-Za-z]+)://([^/]+)(.*)$`); m {
		switch {
		case scheme != "ftp" && scheme != "http" && scheme != "https" && scheme != "gopher":
			cv.Warnf("%q is not a valid URL. Only ftp, gopher, http, and https URLs are allowed here.", value)

		case absPath == "":
			cv.Notef("For consistency, please add a trailing slash to %q.", value)

		default:
			cv.Warnf("%q is not a valid URL.", value)
		}

	} else {
		cv.Warnf("%q is not a valid URL.", value)
	}
}

func (cv *VartypeCheck) UserGroupName() {
	value := cv.Value
	if value != cv.ValueNoVar {
		return
	}
	invalid := invalidCharacters(value, textproc.NewByteSet("---0-9_a-z"))
	if invalid != "" {
		cv.Warnf("User or group name %q contains invalid characters: %s",
			value, invalid)
		return
	}

	if hasPrefix(value, "-") {
		cv.Errorf("User or group name %q must not start with a hyphen.", value)
	}
	if hasSuffix(value, "-") {
		cv.Errorf("User or group name %q must not end with a hyphen.", value)
	}
}

// VariableName checks that the value is a valid variable name to be used in Makefiles.
func (cv *VartypeCheck) VariableName() {
	// TODO: sync with MkParser.Varname
	if cv.Value == cv.ValueNoVar && !matches(cv.Value, `^[A-Z_][0-9A-Z_]*(?:[.].*)?$`) {
		cv.Warnf("%q is not a valid variable name.", cv.Value)
		cv.Explain(
			"Variable names are restricted to only uppercase letters and the",
			"underscore in the basename, and arbitrary characters in the",
			"parameterized part, following the dot.",
			"",
			"Examples:",
			"* PKGNAME",
			"* PKG_OPTIONS.gtk+-2.0")
	}
}

func (cv *VartypeCheck) VariableNamePattern() {
	if cv.Value != cv.ValueNoVar {
		return
	}

	// TODO: sync with MkParser.Varname
	if matches(cv.Value, `^[*A-Z_.][*0-9A-Z_]*(?:[.].*)?$`) {
		return
	}

	cv.Warnf("%q is not a valid variable name pattern.", cv.Value)
	cv.Explain(
		"Variable names are restricted to only uppercase letters and the",
		"underscore in the basename, and arbitrary characters in the",
		"parameterized part, following the dot.",
		"",
		"In addition to these characters, variable name patterns may use",
		"the * placeholder.",
		"",
		"Examples:",
		"* PKGNAME",
		"* PKG_OPTIONS.gtk+-2.0")
}

func (cv *VartypeCheck) Version() {
	value := cv.Value

	if cv.Op == opUseMatch {
		if value != "*" && !matches(value, `^[\d?\[][\w\-.*?\[\]]+$`) {
			cv.Warnf("Invalid version number pattern %q.", value)
			return
		}

		const digit = `(?:\d|\[[\d-]+\])`
		const alnum = `(?:\w|\[[\d-]+\])`
		if m, ver, suffix := match2(value, `^(`+digit+alnum+`*(?:\.`+alnum+`+)*)(\.\*|\*|)$`); m {
			if suffix == "*" && ver != "[0-9]" {
				cv.Warnf("Please use %q instead of %q as the version pattern.", ver+".*", ver+"*")
				cv.Explain(
					"For example, the version \"1*\" also matches \"10.0.0\", which is",
					"probably not intended.")
			}
		}
		return
	}

	if value == cv.ValueNoVar && !matches(value, `^\d[\w.]*$`) {
		cv.Warnf("Invalid version number %q.", value)
	}
}

func (cv *VartypeCheck) WrapperReorder() {
	if !matches(cv.Value, `^reorder:l:([\w\-]+):([\w\-]+)$`) {
		cv.Warnf("Unknown wrapper reorder command %q.", cv.Value)
	}
}

func (cv *VartypeCheck) WrapperTransform() {
	cmd := cv.Value
	switch {
	case hasPrefix(cmd, "rm:-"),
		matches(cmd, `^(R|l|rpath):([^:]+):(.+)$`),
		matches(cmd, `^'?(opt|rename|rm-optarg|rmdir):.*$`),
		cmd == "-e",
		matches(cmd, `^["']?s[|:,]`):
		break

	default:
		cv.Warnf("Unknown wrapper transform command %q.", cmd)
	}
}

func (cv *VartypeCheck) WrkdirSubdirectory() {
	cv.Pathname()
}

// WrksrcSubdirectory checks a directory relative to ${WRKSRC},
// for use in CONFIGURE_DIRS and similar variables.
func (cv *VartypeCheck) WrksrcSubdirectory() {
	if m, _, rest := match2(cv.Value, `^(\$\{WRKSRC\})(?:/(.*))?`); m {
		if rest == "" {
			rest = "."
		}

		fix := cv.Autofix()
		fix.Notef("You can use %q instead of %q.", rest, cv.Value)
		fix.Explain(
			"These directories are interpreted relative to ${WRKSRC}.")
		fix.Replace(cv.Value, rest)
		fix.Apply()

	} else if cv.ValueNoVar == "" {
		// The value of another variable

	} else if !matches(cv.ValueNoVar, `^(?:\.|[0-9A-Za-z_@][-0-9A-Za-z_@./+]*)$`) {
		cv.Warnf("%q is not a valid subdirectory of ${WRKSRC}.", cv.Value)
		cv.Explain(
			"WRKSRC should be defined so that there is no need to do anything",
			"outside of this directory.",
			"",
			"Example:",
			"",
			"\tWRKSRC=\t${WRKDIR}",
			"\tCONFIGURE_DIRS=\t${WRKSRC}/lib ${WRKSRC}/src",
			"\tBUILD_DIRS=\t${WRKSRC}/lib ${WRKSRC}/src ${WRKSRC}/cmd",
			"",
			seeGuide("Directories used during the build process", "build.builddirs"))
	}

	// TODO: Check for ${WRKSRC}/.. or a simple .., like in checkTextWrksrcDotDot.
}

func (cv *VartypeCheck) Yes() {
	switch cv.Op {
	case opUseMatch:
		cv.Warnf("%s should only be used in a \".if defined(...)\" condition.", cv.Varname)
		cv.Explain(
			"This variable can have only two values: defined or undefined.",
			"When it is defined, it means \"yes\", even when its value is",
			"\"no\" or the empty string.",
			"",
			"Therefore, it should not be checked by comparing its value",
			"but using \".if defined(VARNAME)\" alone.")

	default:
		if cv.Value != "YES" && cv.Value != "yes" {
			cv.Warnf("%s should be set to YES or yes.", cv.Varname)
			cv.Explain(
				"This variable means \"yes\" if it is defined, and \"no\" if it is undefined.",
				"Even when it has the value \"no\", this means \"yes\".",
				"Therefore when it is defined, its value should correspond to its meaning.")
		}
	}
}

// YesNo checks for variables that can be set to either yes or no. Undefined
// means no.
//
// Most of these variables use the lowercase yes/no variant. Some use the
// uppercase YES/NO, and the mixed forms Yes/No are practically never seen.
// Testing these variables using the however-mixed pattern is done solely
// because writing this pattern is shorter than repeating the variable name.
func (cv *VartypeCheck) YesNo() {
	const (
		yes1 = "[yY][eE][sS]"
		yes2 = "[Yy][Ee][Ss]"
		no1  = "[nN][oO]"
		no2  = "[Nn][Oo]"
	)
	if cv.Op == opUseMatch {
		switch cv.Value {
		case yes1, yes2, no1, no2:
			break
		default:
			cv.Warnf("%s should be matched against %q or %q, not %q.", cv.Varname, yes1, no1, cv.Value)
		}
	} else if cv.Op == opUseCompare {
		cv.Warnf("%s should be matched against %q or %q, not compared with %q.", cv.Varname, yes1, no1, cv.Value)
		cv.Explain(
			"The yes/no value can be written in either upper or lower case, and",
			"both forms are actually used.",
			"As long as this is the case, when checking the variable value,",
			"both must be accepted.")
	} else if !matches(cv.Value, `^(?:YES|yes|NO|no)$`) {
		cv.Warnf("%s should be set to YES, yes, NO, or no.", cv.Varname)
	}
}

func (cv *VartypeCheck) YesNoIndirectly() {
	if cv.ValueNoVar != "" {
		cv.YesNo()
	}
}