-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTDNumberState.j
122 lines (98 loc) · 2.33 KB
/
TDNumberState.j
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
@import "TDTokenizerState.j"
@implementation TDNumberState : TDTokenizerState
{
BOOL allowsTrailingDot;
BOOL gotADigit;
BOOL negative;
int c;
float floatValue;
}
- (TDToken)nextTokenFromReader:(TDReader)r startingWith:(int)cin tokenizer:(TDTokenizer)t
{
[self reset];
negative = NO;
var originalCin = cin;
if ('-' == cin) {
negative = YES;
cin = [r read];
[self append:'-'];
} else if ('+' == cin) {
cin = [r read];
[self append:'+'];
}
[self reset:cin];
if ('.' == c) {
[self parseRightSideFromReader:r];
} else {
[self parseLeftSideFromReader:r];
[self parseRightSideFromReader:r];
}
// erroneous ., +, or -
if (!gotADigit) {
if (negative && -1 != c) { // ??
[r unread];
}
return [t.symbolState nextTokenFromReader:r startingWith:originalCin tokenizer:t];
}
if (-1 != c) {
[r unread];
}
if (negative) {
floatValue = -floatValue;
}
return [TDToken tokenWithTokenType:TDTokenTypeNumber stringValue:[self bufferedString] floatValue:[self value]];
}
- (float)value
{
return floatValue;
}
- (float)absorbDigitsFromReader:(TDReader)r isFraction:(BOOL)isFraction
{
var divideBy = 1.0,
v = 0.0;
while (1) {
if (isdigit(c)) {
[self append:c];
gotADigit = YES;
v = v * 10.0 + (c - '0');
c = [r read];
if (isFraction) {
divideBy *= 10.0;
}
} else {
break;
}
}
if (isFraction) {
v = v / divideBy;
}
return v;
}
- (void)parseLeftSideFromReader:(TDReader)r
{
floatValue = [self absorbDigitsFromReader:r isFraction:NO];
}
- (void)parseRightSideFromReader:(TDReader)r
{
if ('.' == c)
{
var n = [r read],
nextIsDigit = isdigit(n);
if (-1 != n)
[r unread];
if (nextIsDigit || allowsTrailingDot) {
[self append:'.'];
if (nextIsDigit) {
c = [r read];
floatValue += [self absorbDigitsFromReader:r isFraction:YES];
}
}
}
}
- (void)reset:(int)cin
{
gotADigit = NO;
floatValue = 0.0;
c = cin;
}
@end