This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrange.js
95 lines (83 loc) · 2.33 KB
/
range.js
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
/*
* Copyright (c) 2015-2016, Salesforce.com, Inc.
* All rights reserved.
* Licensed under the MIT license.
* For full license text, see LICENSE.md file in the repo root or
* https://opensource.org/licenses/MIT
*/
'use strict';
let errors = require('../errors.js');
let Type = require('./type.js');
let Value = require('./value.js');
let NumberValue = require('./number.js').Value;
class RangeValue extends Value {
constructor(type) {
super(type);
this.value = this.type.low;
}
assign(newValue) {
if (typeof newValue == 'number') {
if (newValue < this.type.low || newValue > this.type.high) {
throw new errors.Bounds(`Cannot assign value of ${newValue} to range ${this.type.getName()}: ${this.type.low}..${this.type.high};`);
}
this.value = newValue;
} else if (newValue instanceof NumberValue) {
return this.assign(newValue.value);
} else if (newValue instanceof RangeValue) {
return this.assign(newValue.value);
} else {
let t = 'undefined';
if (newValue !== undefined) {
t = `${newValue.type}`;
}
throw new errors.Internal(`Trying to assign ${t} to range ${this.type.getName()}: ${this.type.low}..${this.type.high};`);
}
}
assignJSON(spec) {
this.assign(spec);
}
equals(other) {
if (typeof other == 'number') {
return this.value == other;
} else if (other instanceof RangeValue || other instanceof NumberValue) {
return this.value == other.value;
} else {
throw new errors.Internal(`Trying to compare ${other.type} to range ${this.type.getName()}: ${this.type.low}..${this.type.high};`);
}
}
innerToString() {
return `${this.value}`;
}
toString() {
return `${this.value}`;
}
toJSON() {
return this.value;
}
}
class RangeType extends Type {
constructor(decl, env, name) {
super(decl, env, name);
this.low = this.decl.low.value;
this.high = this.decl.high.value;
}
equals(other) {
return (other instanceof RangeType &&
this.low == other.low &&
this.high == other.high);
}
makeDefaultValue() {
return new RangeValue(this);
}
toString() {
let name = this.getName();
if (name !== undefined) {
return name;
}
return `${this.low}..${this.high}`;
}
}
module.exports = {
Type: RangeType,
Value: RangeValue,
};