-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSource.rb
132 lines (122 loc) · 2.86 KB
/
Source.rb
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
# encoding: utf-8
module Delta
class Source
attr_accessor(:fileName,:file ,:currentChar)
attr_reader(:position, :line, :prePosition)
attr_reader(:lineState,:charCode)
def initialize(file)
@fileName = file
@position = -1;
@line = 1;
@lineState = 0
end
def open
if File.exists?(@fileName) && !File.directory?(@fileName)
@file = File.new(@fileName, "r")
else
puts "file is not exists. --- " + @fileName
exit
end
end
def getc
if @file
return @file.getc
else
puts "File was not open " + @fileName
exit
end
end
def ungetc(char)
if @file
if ["\n","\r"].include?(char)
@line -= 1;
end
@position = @prePosition
@file.ungetc(char)
else
puts "File was not open " + @fileName
exit
end
end
def takeChar
@currentChar = getc
sourceInfo (@currentChar)
end
def fetchFirstChar
@currentChar = getc
skipBOM
sourceInfo (@currentChar)
return @currentChar
end
def screen (char)
if @file
if ( char != nil ) #not at end of file
sourceInfo(char)
else
updateSourceInfo
@charCode = -1
end
else
puts "File was not open " + @fileName
exit
end
end
private
def skipBOM
if @currentChar.ord == 61371 #0xef 0xbb
ck = getc
n = 0
cl = -1
ck.each_byte do |c|
n = n + 1
cl = c
end
if cl == 191 && n == 1 #cl is 0xbf
#0xef 0xbb 0xbf is a BOM sequence
@currentChar = getc
sourceInfo (@currentChar)
else
ungetc(ck)
end
end
end
private
def sourceInfo (char)
@prePosition = @position
@position += 1
detectNewLine(char)
if char != nil
@charCode = char.ord
else
@charCode = -1
end
end
private
def detectNewLine (char)
if @lineState == 0
if ["\n","\r"].include?(char)
#puts "enter",char,@position
#updateSourceInfo
@lineState = 1
end
elsif @lineState == 1
if not (["\n","\r"].include?(char) )
updateSourceInfo
end
@lineState = 0
#if not ["\n","\r"].include?(char)
# @lineSate = 0
#else
# updateSourceInfo
# @lineSate = 0
#end
end
end
private
def updateSourceInfo
@line += 1
@prePosition = @position
@position = 0
end
end
end