File: StringScanner.cs

package info (click to toggle)
dlr-languages 20090805%2Bgit.e6b28d27%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 51,484 kB
  • ctags: 59,257
  • sloc: cs: 298,829; ruby: 159,643; xml: 19,872; python: 2,820; yacc: 1,960; makefile: 96; sh: 65
file content (502 lines) | stat: -rw-r--r-- 18,230 bytes parent folder | download
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
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System.Runtime.InteropServices;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using System.Text;
using System.Text.RegularExpressions;
using IronRuby.Builtins;
using IronRuby.Runtime;
using System.Security.Permissions;
using System.Runtime.Serialization;

namespace IronRuby.StandardLibrary.StringScanner {

    [RubyClass("StringScanner")]
    public sealed class StringScanner : RubyObject {
        private MutableString/*!*/ _scanString;
        private int _previousPosition;
        private int _currentPosition;
        private int _foundPosition;
        private MutableString _lastMatch;
        private GroupCollection _lastMatchingGroups;

        #region Construction

        public StringScanner(RubyClass/*!*/ rubyClass) 
            : base(rubyClass) {
            _scanString = MutableString.FrozenEmpty;
        }

#if !SILVERLIGHT
        public StringScanner(SerializationInfo/*!*/ info, StreamingContext context) 
            : base(info, context) {
            // TODO: deserialize
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo/*!*/ info, StreamingContext context) {
            base.GetObjectData(info, context);
            // TODO: serialize
        }
#endif

        protected override RubyObject/*!*/ CreateInstance() {
            return new StringScanner(ImmediateClass.NominalClass);
        }

        private void InitializeFrom(StringScanner/*!*/ other) {
            _currentPosition = other._currentPosition;
            _foundPosition = other._foundPosition;
            _lastMatch = other._lastMatch;
            _lastMatchingGroups = other._lastMatchingGroups;
            _previousPosition = other._previousPosition;
            _scanString = other.ScanString;
        }

        [RubyConstructor]
        public static StringScanner/*!*/ Create(RubyClass/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ scan) {
            var result = new StringScanner(self);
            result.ScanString = scan;
            result.Reset();
            return result;
        }

        [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)]
        public static void Reinitialize(StringScanner/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ scan) {
            self.ScanString = scan;
            self.Reset();
        }

        [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)]
        public static void InitializeFrom(StringScanner/*!*/ self, [DefaultProtocol, NotNull]StringScanner/*!*/ other) {
            self.InitializeFrom(other);
        }

        #endregion

        #region Singleton Methods

        /// <summary>
        /// This method is defined for backwards compatibility
        /// </summary>
        [RubyMethod("must_C_version", RubyMethodAttributes.PublicSingleton)]
        public static object MustCVersion(object self) {
            return self;
        }

        #endregion

        #region Public Instance Methods

        [RubyMethod("<<")]
        [RubyMethod("concat")]
        public static StringScanner Concat(StringScanner/*!*/ self, MutableString str) {
            self.ScanString.Append(str);
            return self;
        }

        [RubyMethod("[]")]
        public static MutableString GetMatchSubgroup(StringScanner/*!*/ self, int subgroup) {
            if (subgroup == 0 && self.LastMatch != null) {
                return MutableString.Create(self.LastMatch);
            }
            if (self.LastMatchingGroups == null) {
                return null;
            }
            if (subgroup < 0) {
                subgroup = self.LastMatchingGroups.Count - subgroup;
            }
            if (subgroup >= self.LastMatchingGroups.Count) {
                return null;
            }
            return MutableString.Create(self.LastMatchingGroups[subgroup].ToString());
        }

        [RubyMethod("beginning_of_line?")]
        [RubyMethod("bol?")]
        public static bool BeginningOfLine(StringScanner/*!*/ self) {
            return (self.CurrentPosition == 0) || (self.ScanString.GetChar(self.CurrentPosition - 1) == '\n');
        }

        [RubyMethod("check")]
        public static MutableString Check(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            return (ScanFull(self, pattern, false, true) as MutableString);
        }

        [RubyMethod("check_until")]
        public static MutableString CheckUntil(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            return (SearchFull(self, pattern, false, true) as MutableString);
        }

        [RubyMethod("empty?")]
        [RubyMethod("eos?")]
        public static bool EndOfLine(StringScanner/*!*/ self) {
            return self.CurrentPosition >= self.Length;
        }

        [RubyMethod("exist?")]
        public static int? Exist(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            if (!self.Match(pattern, false, false)) {
                return null;
            }
            return self.FoundPosition + self.LastMatch.Length;
        }

        [RubyMethod("get_byte")]
        [RubyMethod("getbyte")]
        public static MutableString GetByte(StringScanner/*!*/ self) {
            if (self.CurrentPosition >= self.Length) {
                return null;
            }
            self.PreviousPosition = self.CurrentPosition;
            self.FoundPosition = self.CurrentPosition;
            self.LastMatch = self.ScanString.GetSlice(self.CurrentPosition++, 1);
            return MutableString.Create(self.LastMatch);
        }

        [RubyMethod("getch")]
        public static MutableString GetChar(StringScanner/*!*/ self) {
            if (self.CurrentPosition >= self.Length) {
                return null;
            }
            self.PreviousPosition = self.CurrentPosition;
            self.FoundPosition = self.CurrentPosition;
            self.LastMatch = self.ScanString.GetSlice(self.CurrentPosition++, 1);
            return MutableString.Create(self.LastMatch);
        }

        [RubyMethod("inspect")]
        [RubyMethod("to_s")]
        public static MutableString ToString(StringScanner/*!*/ self) {
            return MutableString.Create(self.ToString());
        }

        [RubyMethod("match?")]
        public static int? Match(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            if (!self.Match(pattern, true, false)) {
                return null;
            }
            return self.LastMatch.GetLength();
        }

        [RubyMethod("matched")]
        public static MutableString Matched(StringScanner/*!*/ self) {
            if (self.LastMatch == null) {
                return null;
            }
            return MutableString.Create(self.LastMatch);
        }

        [RubyMethod("matched?")]
        public static bool WasMatched(StringScanner/*!*/ self) {
            return (self.LastMatch != null);
        }

        [RubyMethod("matched_size")]
        [RubyMethod("matchedsize")]
        public static int? MatchedSize(StringScanner/*!*/ self) {
            if (self.LastMatch == null) {
                return null;
            }
            return self.LastMatch.Length;
        }

        [RubyMethod("peek")]
        [RubyMethod("peep")]
        public static MutableString Peek(StringScanner/*!*/ self, int len) {
            if (len < 0) {
                throw RubyExceptions.CreateArgumentError("negative string size (or size too big)");
            }
            int maxlen = self.Length - self.CurrentPosition;
            if (len > maxlen) {
                len = maxlen;
            }
            if (self.CurrentPosition >= self.Length || len == 0) {
                return MutableString.CreateMutable();
            }
            return self.ScanString.GetSlice(self.CurrentPosition, len);
        }

        [RubyMethod("pos")]
        [RubyMethod("pointer")]
        public static int GetCurrentPosition(StringScanner/*!*/ self) {
            return self.CurrentPosition;
        }

        [RubyMethod("pos=")]
        [RubyMethod("pointer=")]
        public static int SetCurrentPosition(StringScanner/*!*/ self, int newPosition) {
            int newPos = newPosition;
            if (newPos < 0) {
                newPos = self.Length - self.CurrentPosition;
            }
            if (newPos > self.Length) {
                throw RubyExceptions.CreateRangeError("index out of range");
            }
            self.CurrentPosition = newPos;
            return newPosition;
        }

        [RubyMethod("post_match")]
        public static MutableString PostMatch(StringScanner/*!*/ self) {
            if (self.LastMatch == null) {
                return null;
            }
            int position = self.FoundPosition + self.LastMatch.Length;
            int len = self.Length - position;
            if (len <= 0) {
                return MutableString.CreateMutable();
            }
            return self.ScanString.GetSlice(position, len);
        }

        [RubyMethod("pre_match")]
        public static MutableString PreMatch(StringScanner/*!*/ self) {
            if (self.LastMatch == null) {
                return null;
            }
            return self.ScanString.GetSlice(0, self.FoundPosition);
        }

        [RubyMethod("reset")]
        public static StringScanner Reset(StringScanner/*!*/ self) {
            self.Reset();
            return self;
        }

        [RubyMethod("rest")]
        public static MutableString Rest(StringScanner/*!*/ self) {
            int len = self.Length - self.CurrentPosition;
            if (len <= 0) {
                return MutableString.CreateMutable();
            }
            return self.ScanString.GetSlice(self.CurrentPosition, len);
        }

        [RubyMethod("rest?")]
        public static bool IsRestLeft(StringScanner/*!*/ self) {
            return self.CurrentPosition < self.Length;
        }

        [RubyMethod("rest_size")]
        [RubyMethod("restsize")]
        public static int RestSize(StringScanner/*!*/ self) {
            return (self.CurrentPosition < self.Length) ? (self.Length - self.CurrentPosition) : 0;
        }

        [RubyMethod("scan")]
        public static MutableString Scan(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            return (ScanFull(self, pattern, true, true) as MutableString);
        }

        [RubyMethod("scan_full")]
        public static object ScanFull(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern, bool advance_pointer_p, bool return_string_p) {
            bool match = self.Match(pattern, true, advance_pointer_p);
            object result = null;
            if (match) {
                if (return_string_p) {
                    result = MutableString.Create(self.LastMatch);
                } else {
                    result = self.LastMatch.Length;
                }
            }
            return result;
        }

        [RubyMethod("scan_until")]
        public static MutableString ScanUntil(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            return (SearchFull(self, pattern, true, true) as MutableString);
        }

        [RubyMethod("search_full")]
        public static object SearchFull(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern, bool advance_pointer_p, bool return_string_p) {
            bool match = self.Match(pattern, false, advance_pointer_p);
            object result = null;
            if (match) {
                int length = self.LastMatch.Length + (self.FoundPosition - self.PreviousPosition);
                if (return_string_p) {
                    result = self.ScanString.GetSlice(self.PreviousPosition, length);
                } else {
                    result = length;
                }
            }
            return result;
        }

        [RubyMethod("skip")]
        public static int? Skip(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            bool match = self.Match(pattern, true, true);
            if (!match) {
                return null;
            }
            return (self.CurrentPosition - self.PreviousPosition);
        }

        [RubyMethod("skip_until")]
        public static int? SkipUntil(StringScanner/*!*/ self, [NotNull]RubyRegex/*!*/ pattern) {
            bool match = self.Match(pattern, false, true);
            if (!match) {
                return null;
            }
            return (self.CurrentPosition - self.PreviousPosition);
        }

        [RubyMethod("string")]
        public static MutableString GetString(StringScanner/*!*/ self) {
            return self.ScanString;
        }

        [RubyMethod("string=")]
        public static MutableString SetString(RubyContext/*!*/ context, StringScanner/*!*/ self, [NotNull]MutableString/*!*/ str) {
            self.ScanString = (MutableString)KernelOps.Freeze(context, MutableString.Create(str));
            self.Reset();
            return str;
        }

        [RubyMethod("clear")]
        [RubyMethod("terminate")]
        public static StringScanner Clear(StringScanner/*!*/ self) {
            self.Reset();
            self.CurrentPosition = self.Length;
            return self;
        }

        [RubyMethod("unscan")]
        public static StringScanner Unscan(StringScanner/*!*/ self) {
            if (self.LastMatch == null) {
                // throw Exception StringScanner::Error
                throw RubyExceptions.CreateRangeError("unscan failed: previous match had failed");
            }
            int position = self.PreviousPosition;
            self.Reset();
            self.CurrentPosition = position;
            return self;
        }
        #endregion

        #region Helpers

        private bool Match(RubyRegex/*!*/ pattern, bool currentPositionOnly, bool advancePosition) {
            Match match = pattern.Match(_scanString, _currentPosition);
            _lastMatch = null;
            _lastMatchingGroups = null;
            _foundPosition = 0;
            if (!match.Success) {
                return false;
            }
            if (currentPositionOnly && match.Index != _currentPosition) {
                return false;
            }
            int length = (match.Index - _currentPosition) + match.Length;
            _foundPosition = match.Index;
            _previousPosition = _currentPosition;
            _lastMatch = _scanString.GetSlice(_foundPosition, match.Length);
            _lastMatchingGroups = match.Groups;
            if (advancePosition) {
                _currentPosition += length;
            }
            return true;
        }

        #endregion 

        
        private int PreviousPosition {
            get { return _previousPosition; }
            set { _previousPosition = value; }
        }

        private int CurrentPosition {
            get { return _currentPosition; }
            set { _currentPosition = value; }
        }

        private int Length {
            get { return _scanString.Length; }
        }

        private MutableString ScanString {
            get { return _scanString; }
            set { _scanString = value; }
        }

        private int FoundPosition {
            get { return _foundPosition; }
            set { _foundPosition = value; }
        }

        private MutableString LastMatch {
            set { _lastMatch = value; }
            get { return _lastMatch; }
        }

        private GroupCollection LastMatchingGroups {
            get { return _lastMatchingGroups; }
        }

        private void Reset() {
            _previousPosition = 0;
            _currentPosition = 0;
            _foundPosition = 0;
            _lastMatch = null;
            _lastMatchingGroups = null;
        }

        public override string ToString() {
            // #<StringScanner 0/11 @ "test ...">
            byte[] scanstr = ScanString.ToByteArray();
            StringBuilder sb = new StringBuilder("#<StringScanner ");
            if (CurrentPosition >= Length || CurrentPosition < 0) {
                sb.Append("fin >");
                return sb.ToString();
            }

            sb.AppendFormat("{0}/{1}", CurrentPosition, scanstr.Length);
            if (CurrentPosition > 0) {
                sb.Append(" \"");
                int len = CurrentPosition;
                if (len > 5) {
                    len = 5;
                    sb.Append("...");
                }
                for (int i = CurrentPosition - len; i < CurrentPosition; i++) {
                    MutableString.AppendCharRepresentation(sb, scanstr[i], -1, true, true, '"', -1);
                }
                sb.Append('"');
            }
            sb.Append(" @ ");
            if (CurrentPosition < scanstr.Length) {
                int len = scanstr.Length - CurrentPosition;
                bool ellipsis = false;
                if (len > 5) {
                    len = 5;
                    ellipsis = true;
                }
                sb.Append('"');
                for (int i = CurrentPosition; i < CurrentPosition + len; i++) {
                    MutableString.AppendCharRepresentation(sb, scanstr[i], -1, true, true, '"', -1);
                }
                if (ellipsis) {
                    sb.Append("...");
                }
                sb.Append('"');
            }
            sb.Append('>');
            return sb.ToString();
        }
    }
}