-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
610 lines (514 loc) · 15 KB
/
validation.go
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
package questions
import (
"errors"
"fmt"
"github.com/benoitkugler/maths-online/server/src/maths/expression"
)
// maxFunctionBound is the maximum value a function
// may reached. Higher values are either a bug, or won't be properly
// displayed on the student client
const maxFunctionBound = 100
type ErrParameters struct {
Origin string
Details string
}
func (err ErrParameters) Error() string {
return fmt.Sprintf("invalid random parameters in %s: %s", err.Origin, err.Details)
}
// Validate ensure the given `Parameters` are sound,
// by parsing the expression, checking for duplicate parameters,
// and detecting definition cycles.
// It the error is not nil, it will be of type `ErrParameters`.
// Once called without error, `ToMap` may be safely used.
func (pr Parameters) Validate() error {
params := expression.NewRandomParameters()
for _, item := range pr {
err := item.mergeTo(params)
if err != nil {
return ErrParameters{
Origin: item.String(),
Details: err.Error(),
}
}
}
if params.IsDefined(expression.Variable{Name: 'e'}) {
return ErrParameters{
Origin: "e = ",
Details: "La variable e n'est pas autorisée (car utilisée pour exp).",
}
}
err := params.Validate()
if err != nil {
return ErrParameters{
Origin: "Paramètres aléatoires",
Details: err.Error(),
}
}
return nil
}
type errEnonce struct {
Error string // detailed error
Block int // index of the invalid block
Vars map[string]string // the actual values used when the error was encountered, or nil
}
type ErrorKind uint8
const (
ErrParameters_ ErrorKind = iota
ErrEnonce
ErrCorrection
)
// ErrQuestionInvalid is returned by Question.Validate()
// It is either an error about the random parameters, or the blocks content (enonce or correction).
type ErrQuestionInvalid struct {
ErrParameters ErrParameters
ErrEnonce errEnonce
ErrCorrection errEnonce
Kind ErrorKind // indicates which field is valid
}
func (e ErrQuestionInvalid) Error() string {
switch e.Kind {
case ErrParameters_:
return fmt.Sprintf("invalid question parameters: %v", e.ErrParameters)
case ErrEnonce:
return fmt.Sprintf("invalid question blocks: %v", e.ErrEnonce)
case ErrCorrection:
return fmt.Sprintf("invalid correction blocks: %v", e.ErrCorrection)
default:
panic("exhaustive switch")
}
}
func (en Enonce) validate(params *expression.RandomParameters) (bool, errEnonce) {
en = en.expandText()
// setup the validators
var err error
validators := make([]validator, len(en))
for i, block := range en {
validators[i], err = block.setupValidator(params)
if err != nil {
return false, errEnonce{Block: i, Error: err.Error()}
}
}
// reuse memory
inst := expression.NewInstantiater(*params)
const nbTries = 1_000
for try := 0; try < nbTries; try++ {
// instantiate the parameters for this try
inst.Reset()
vars, _ := inst.Instantiate()
// run through the blocks
for i, v := range validators {
err := v.validate(vars)
if err != nil {
// export the current parameters as strings
varsS := make(map[string]string, len(vars))
for k, v := range vars {
varsS[k.String()] = v.String()
}
return false, errEnonce{Block: i, Error: err.Error(), Vars: varsS}
}
}
}
return true, errEnonce{}
}
// Validate ensure the random parameters and enonce blocks are sound.
// If not, an `ErrQuestionInvalid` is returned.
func (qu QuestionPage) Validate() error {
if err := qu.Parameters.Validate(); err != nil {
return ErrQuestionInvalid{Kind: ErrParameters_, ErrParameters: err.(ErrParameters)}
}
params := qu.Parameters.ToMap()
if ok, err := qu.Enonce.validate(params); !ok {
return ErrQuestionInvalid{Kind: ErrEnonce, ErrEnonce: err}
}
if ok, err := qu.Correction.validate(params); !ok {
return ErrQuestionInvalid{Kind: ErrCorrection, ErrCorrection: err}
}
return nil
}
type validator interface {
// validate the field given the instantiated values
validate(vars expression.Vars) error
}
type noOpValidator struct{}
func (noOpValidator) validate(vars expression.Vars) error { return nil }
type parsedCoord struct {
X, Y *expression.Expr
}
func (c parsedCoord) validate(vars expression.Vars, checkPrecision bool) error {
if err := c.X.IsValidNumber(vars, checkPrecision, true); err != nil {
return err
}
if err := c.Y.IsValidNumber(vars, checkPrecision, true); err != nil {
return err
}
return nil
}
type linearEquationValidator struct {
expr *expression.Expr
}
func (v linearEquationValidator) validate(vars expression.Vars) error {
return v.expr.IsValidLinearEquation(vars)
}
type variationTableValidator struct {
label TextParts
xs []*expression.Expr
fxs []*expression.Expr
}
func (v variationTableValidator) validate(vars expression.Vars) error {
_, err := v.label.instantiateAndMerge(vars)
if err != nil {
return err
}
for _, c := range v.fxs {
err := c.IsValidNumber(vars, false, true)
if err != nil {
return err
}
}
return expression.AreSortedNumbers(v.xs, vars)
}
type signTableValidator struct {
labels []TextParts
}
func (v signTableValidator) validate(vars expression.Vars) error {
for _, label := range v.labels {
_, err := label.instantiateAndMerge(vars)
if err != nil {
return err
}
}
return nil
}
type figureValidator struct {
pointNames []*expression.Expr
points []*expression.Expr // X,Y
references []*expression.Expr
circlesDims []*expression.Expr // center and radius
lines [][2]*expression.Expr // A, B
}
func (v figureValidator) pointStrings(vars expression.Vars) map[string]bool {
out := make(map[string]bool, len(v.pointNames))
for _, expr := range v.pointNames {
expr = expr.Copy()
expr.Substitute(vars)
out[expr.AsLaTeX()] = true
}
return out
}
func (v figureValidator) validate(vars expression.Vars) error {
for _, point := range v.points {
if err := point.IsValidNumber(vars, false, true); err != nil {
return err
}
}
points := v.pointStrings(vars)
// check for duplicates ...
if len(points) != len(v.pointNames) {
return errors.New("Les noms des points ne sont pas distincts.")
}
// .. and undefined points
for _, ref := range v.references {
ref = ref.Copy()
ref.Substitute(vars)
resolvedRef := ref.AsLaTeX()
if hasPoint := points[resolvedRef]; !hasPoint {
return fmt.Errorf("L'expression %s ne définit pas un point connu.", resolvedRef)
}
}
// check for valid circle dimensions
for _, circleNum := range v.circlesDims {
if err := circleNum.IsValidNumber(vars, false, true); err != nil {
return err
}
}
// check for affine line coefficients
for _, line := range v.lines {
if err := line[0].IsValidNumber(vars, false, false); err != nil {
return err
}
if err := line[1].IsValidNumber(vars, false, true); err != nil {
return err
}
}
return nil
}
type functionValidator struct {
label Interpolated
domain expression.Domain
expression.FunctionExpr
}
func newFunctionValidator(fn FunctionDefinition, params *expression.RandomParameters) (functionValidator, error) {
fnExpr, from, to, err := fn.parse()
if err != nil {
return functionValidator{}, err
}
// check that the function variable is not used
if params.IsDefined(fn.Variable) {
return functionValidator{}, fmt.Errorf("La variable <b>%s</b> est déjà utilisée dans les paramètres aléatoires.", fn.Variable)
}
_, err = fn.Decoration.Label.parse()
if err != nil {
return functionValidator{}, err
}
return functionValidator{label: fn.Decoration.Label, FunctionExpr: fnExpr, domain: expression.Domain{From: from, To: to}}, nil
}
type areaVData struct {
top, bottom TextParts
domain expression.Domain
}
type functionPointVData struct {
fnLabel TextParts
x *expression.Expr
}
type functionsGraphValidator struct {
functions []functionValidator
variationValidator []variationTableValidator
sequences []functionValidator
areas []areaVData
points []functionPointVData
}
func (v functionsGraphValidator) validate(vars expression.Vars) error {
for _, f := range v.functions {
if err := f.FunctionExpr.IsValidAsFunction(f.domain, vars, maxFunctionBound); err != nil {
return err
}
}
for _, varTable := range v.variationValidator {
if err := varTable.validate(vars); err != nil {
return err
}
}
for _, f := range v.sequences {
if err := f.FunctionExpr.IsValidAsSequence(f.domain, vars, maxFunctionBound); err != nil {
return err
}
}
// checks that function with same label are defined on non overlapping intervals,
// so that area references can't be ambiguous
byNames := make(map[string][]expression.Domain)
for _, fn := range v.functions {
label, err := fn.label.instantiateAndMerge(vars)
if err != nil {
return err
}
byNames[label] = append(byNames[label], fn.domain)
}
for _, vt := range v.variationValidator {
label, err := vt.label.instantiateAndMerge(vars)
if err != nil {
return err
}
byNames[label] = append(byNames[label], expression.Domain{
From: vt.xs[0], To: vt.xs[len(vt.xs)-1], // vt.validate checks that these calls are safe
})
}
for name, domains := range byNames {
if err := expression.AreDisjointsDomains(domains, vars); err != nil {
return fmt.Errorf("Pour la fonction %s, %s.", name, err)
}
}
// checks that areas are referencing known functions
// and that the domains are valid
for _, area := range v.areas {
top, err := area.top.instantiateAndMerge(vars)
if err != nil {
return err
}
bottom, err := area.bottom.instantiateAndMerge(vars)
if err != nil {
return err
}
domainsTop := byNames[top]
if top == "" {
domainsTop = []expression.Domain{{}} // use the abscisse axis, which has no constraints
}
if len(domainsTop) == 0 {
return fmt.Errorf("La fonction %s n'est pas définie.", top)
}
domainsBottom := byNames[bottom]
if bottom == "" {
domainsBottom = []expression.Domain{{}} // use the abscisse axis, which has no constraints
}
if len(domainsBottom) == 0 {
return fmt.Errorf("La fonction %s n'est pas définie.", bottom)
}
// check that the domain in included in one of the domain for f1 and f2
if err := area.domain.IsIncludedIntoOne(domainsTop, vars); err != nil {
return err
}
if err := area.domain.IsIncludedIntoOne(domainsBottom, vars); err != nil {
return err
}
}
// check that points reference known functions and
// are in valid domains
for _, point := range v.points {
fnLabel, err := point.fnLabel.instantiateAndMerge(vars)
if err != nil {
return err
}
domains := byNames[fnLabel]
if fnLabel == "" { // use the abscisse axis, which has no constraints
domains = []expression.Domain{{}}
}
if len(domains) == 0 {
return fmt.Errorf("La fonction %s n'est pas définie.", fnLabel)
}
// check that the abscisse is in one domain
if err := point.x.IsIncludedIntoOne(domains, vars); err != nil {
return err
}
}
return nil
}
type numberValidator struct {
expr *expression.Expr
}
func (v numberValidator) validate(vars expression.Vars) error {
// note that we dont allow non decimal solutions, since it is confusing for the student.
// they should rather be handled with an expression field, or rounded using the
// builtin round() function
return v.expr.IsValidNumber(vars, true, true)
}
type radioValidator struct {
proposalsLength int
expr *expression.Expr
}
func (v radioValidator) validate(vars expression.Vars) error {
return v.expr.IsValidIndex(vars, v.proposalsLength)
}
type geometricConstructionValidator struct {
field validator
background validator
}
func (v geometricConstructionValidator) validate(vars expression.Vars) error {
if err := v.field.validate(vars); err != nil {
return err
}
return v.background.validate(vars)
}
type gfPointValidator parsedCoord
func (v gfPointValidator) validate(vars expression.Vars) error {
return parsedCoord(v).validate(vars, false)
}
type gfVectorValidator struct {
answer parsedCoord
answerOrigin *parsedCoord // optional
}
func (v gfVectorValidator) validate(vars expression.Vars) error {
if err := v.answer.validate(vars, false); err != nil {
return err
}
if v.answerOrigin != nil {
return v.answerOrigin.validate(vars, false)
}
return nil
}
type gfAffineLineValidator struct {
a, b *expression.Expr
}
func (v gfAffineLineValidator) validate(vars expression.Vars) error {
if err := v.a.IsValidNumber(vars, false, false); err != nil {
return err
}
if err := v.b.IsValidNumber(vars, false, true); err != nil {
return err
}
b, err := v.b.Evaluate(vars)
if err != nil {
return err
}
if _, ok := expression.IsInt(b); !ok {
return fmt.Errorf("L'expression %s de B n'est pas un nombre entier (%f).", v.b, b)
}
return nil
}
type functionPointsValidator struct {
xGrid []*expression.Expr
function functionValidator
}
// checks the x grid only contains integers values with no duplicates,
// and that the y values are integers.
func (v functionPointsValidator) validate(vars expression.Vars) error {
seen := make(map[int]bool)
fnExpr := expression.FunctionExpr{
Function: v.function.Function.Copy(),
Variable: v.function.Variable,
}
fnExpr.Function.Substitute(vars)
f := fnExpr.Closure()
// checks that all grid values are integers
for _, xExpr := range v.xGrid {
xValue, err := xExpr.Evaluate(vars)
if err != nil {
return err
}
val, ok := expression.IsInt(xValue)
if !ok {
return fmt.Errorf("L'expression %s ne définit par un antécédent <b>entier</b> (%g).", xExpr, expression.RoundFloat(xValue))
}
if seen[val] {
return fmt.Errorf("Les antécédents ne sont pas uniques.")
}
seen[val] = true
y := f(xValue)
if _, ok = expression.IsInt(y); !ok {
return fmt.Errorf("L'expression %s ne définit pas des images <b>entières</b> (%g)", fnExpr.Function, expression.RoundFloat(y))
}
}
return nil
}
// NOTE: as an optimisation, we could parse
// earlier the expression
type treeValidator struct {
data TreeBlock
}
func (v treeValidator) validate(vars expression.Vars) error {
var checkTree func(node TreeNodeAnswer) error
checkTree = func(node TreeNodeAnswer) error {
if node.Value < 0 || node.Value >= len(v.data.EventsProposals) {
return fmt.Errorf("L'index %d n'est pas compatible avec le nombre de propositions.", node.Value)
}
for _, c := range node.Probabilities {
_, err := expression.Parse(c) // we accept any valid expression to allow for instance "x"
if err != nil {
return err
}
}
for _, c := range node.Children {
if err := checkTree(c); err != nil {
return err
}
}
return nil
}
return checkTree(v.data.AnswerRoot)
}
type tableValidator struct {
answer [][]*expression.Expr
}
func (v tableValidator) validate(vars expression.Vars) error {
for _, row := range v.answer {
for _, cell := range row {
if err := cell.IsValidNumber(vars, true, true); err != nil {
return err
}
}
}
return nil
}
type vectorValidator struct {
answer parsedCoord
}
func (v vectorValidator) validate(vars expression.Vars) error {
return v.answer.validate(vars, true)
}
type setValidator struct {
answer *expression.Expr
}
func (sv setValidator) validate(vars expression.Vars) error {
e := sv.answer.Copy()
e.Substitute(vars)
_, err := e.ToBinarySet()
return err
}