forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSourceLocationTracker.cs
More file actions
96 lines (83 loc) · 2.76 KB
/
SourceLocationTracker.cs
File metadata and controls
96 lines (83 loc) · 2.76 KB
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Web.Razor.Parser;
namespace System.Web.Razor.Text
{
public class SourceLocationTracker
{
private int _absoluteIndex = 0;
private int _characterIndex = 0;
private int _lineIndex = 0;
private SourceLocation _currentLocation;
public SourceLocationTracker()
: this(SourceLocation.Zero)
{
}
public SourceLocationTracker(SourceLocation currentLocation)
{
CurrentLocation = currentLocation;
UpdateInternalState();
}
public SourceLocation CurrentLocation
{
get
{
return _currentLocation;
}
set
{
if (_currentLocation != value)
{
_currentLocation = value;
UpdateInternalState();
}
}
}
public void UpdateLocation(char characterRead, char nextCharacter)
{
UpdateCharacterCore(characterRead, nextCharacter);
RecalculateSourceLocation();
}
public SourceLocationTracker UpdateLocation(string content)
{
for (int i = 0; i < content.Length; i++)
{
char nextCharacter = '\0';
if (i < content.Length - 1)
{
nextCharacter = content[i + 1];
}
UpdateCharacterCore(content[i], nextCharacter);
}
RecalculateSourceLocation();
return this;
}
private void UpdateCharacterCore(char characterRead, char nextCharacter)
{
_absoluteIndex++;
if (ParserHelpers.IsNewLine(characterRead) && (characterRead != '\r' || nextCharacter != '\n'))
{
_lineIndex++;
_characterIndex = 0;
}
else
{
_characterIndex++;
}
}
private void UpdateInternalState()
{
_absoluteIndex = CurrentLocation.AbsoluteIndex;
_characterIndex = CurrentLocation.CharacterIndex;
_lineIndex = CurrentLocation.LineIndex;
}
private void RecalculateSourceLocation()
{
_currentLocation = new SourceLocation(_absoluteIndex, _lineIndex, _characterIndex);
}
public static SourceLocation CalculateNewLocation(SourceLocation lastPosition, string newContent)
{
return new SourceLocationTracker(lastPosition).UpdateLocation(newContent).CurrentLocation;
}
}
}