summaryrefslogtreecommitdiff
path: root/cpp.fun
blob: 8884a59ce89ffbbab6fe2b5ae44f0c9aabddaceb (plain)
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
functor Cpp(T: TOKENIZER): CPP = struct

  structure T = T

  type tkPos = T.S.pos
  type t =
    { streams: T.S.t list, fileInfo: T.S.fileInfo list,
      lastPos: tkPos option, firstId: T.S.fileId,
      incDirs: string list }

  datatype tkExp =
    Tk of T.token |
    Id |
    NumConst |
    StrLiteral |
    UnOp |
    BinOp |
    Op

  type tkExpectedVal = string * tkExp list

  exception StreamTooOld
  exception TkExpected of tkExpectedVal

  type tkErrorVal = string * string
  exception TkError of tkErrorVal

  fun create fname incDirs =
  let
    val stream = T.S.create fname
    val info = T.S.convert stream
  in
   { streams = [stream] , fileInfo = [info], lastPos = NONE,
      firstId = #1 info, incDirs }
  end

  fun getLastPos ({ lastPos = NONE, ... }: t) = raise Unreachable
    | getLastPos { lastPos = SOME p, ... } = p

  fun getTopFileInfo ({ streams = top :: _, ... }: t) = T.S.convert top
    | getTopFileInfo _ = raise Unreachable

  val tkExp2str = fn
      (Tk tk) => T.token2str tk
    | Id: tkExp => "identifier"
    | NumConst => "numeric constant"
    | StrLiteral => "string literal"
    | UnOp => "unary operator"
    | BinOp => "binary operator"
    | Op => "operator"

  fun tkPos2str stream (id, pos) =
  let
    val fileInfo =
      case List.find (fn (id', _, _) => id' = id) $ #fileInfo stream of
        NONE => raise StreamTooOld
      | SOME fileInfo => fileInfo
  in
    T.S.ppos2str $ T.S.pos2pposWithFI (id, pos) fileInfo
  end

  fun prepTkError stream pos msg = raise TkError (tkPos2str stream pos, msg)
  fun prepLastTkError stream = prepTkError stream (getLastPos stream)

  fun prepTkExpected (stream: t) pos expList =
    raise TkExpected (tkPos2str stream pos, expList)
  fun prepLastTkExpected stream = prepTkExpected stream
    (getLastPos stream)

  fun tkExpectedPrint (pos, expList) =
  let
    fun tkExps2str [e] [] = tkExp2str e
      | tkExps2str [e] acc =
        (String.concatWith ", " acc ^ " or ") ^ tkExp2str e
      | tkExps2str (e :: ec) acc =
        tkExps2str ec (tkExp2str e :: acc)
      | tkExps2str [] _ = raise Unreachable
  in
    print pos;
    print ":expected ";
    printLn $ tkExps2str expList []
  end

  fun tkErrorPrint (pos, msg) = printLn $ pos ^ ": " ^ msg

  exception EmptyPath

  fun getDirOfCurFile ({ streams = top :: _, ... }: t) =
    OS.Path.getParent $ T.S.getFname top
    | getDirOfCurFile _ = raise Unreachable


  (* TODO: properly handle Size and Path exceptions from concat *)
  fun findPath _ "" _ = raise EmptyPath
    | findPath stream fname true =
    let
      val path = OS.Path.concat (getDirOfCurFile stream, fname)
    in
      (path, TextIO.openIn path)
    end
    | findPath stream fname false =
    let
      fun try (dir :: tail) =
      let
        val fname = OS.Path.concat (dir, fname)
      in
        SOME (fname, TextIO.openIn fname) handle _ => try tail
      end
        | try [] = NONE

      val instream = try (#incDirs stream)
    in
      case instream of
        NONE => findPath stream fname true
      | SOME pair => pair
    end

  fun predSkip stream pred =
  let
    val (c, stream) = T.S.getchar stream
  in
    case c of
      NONE => (NONE, stream)
    | SOME c =>
      if c = #"\n" then
        (NONE, stream)
      else if pred c then
        (SOME $ #2 $ T.S.getPosAfterCharRead stream, stream)
      else
        predSkip stream pred
  end

  fun tryCollect stream =
  let
    val top = hd $ #streams stream

    fun x f = f stream

    fun returnBack top = {
      streams = top :: tl (#streams stream),
      fileInfo = x#fileInfo,
      lastPos = x#lastPos,
      firstId = x#firstId,
      incDirs = x#incDirs
    }

    val (start, s) =
      case predSkip top (fn c => c = #"<") of
        (NONE, _) => raise Unreachable
      | (SOME p, s) => (p, s)

    val (res, s) = predSkip s (fn c => c = #">")
  in
    case res of
      NONE => (NONE, stream)
    | SOME endOff =>
        (SOME $ T.S.getSubstr (start + 1) endOff s, returnBack s)
  end

  fun getToken
    ({ streams = stream :: tail, fileInfo, lastPos, firstId, incDirs }: t) =
  let
    val (tk, stream) = T.getToken stream
  in
    case tk of
      NONE => getToken { streams = tail, fileInfo, lastPos, firstId, incDirs }
    | SOME (pos, tk) =>
        if tk = T.CppInclude then
          handleInclude { streams = stream :: tail, fileInfo,
            lastPos, firstId, incDirs }
        else
          (tk, { streams = stream :: tail, fileInfo,
              lastPos = SOME pos, firstId, incDirs })
  end
    | getToken
        { streams = [], fileInfo, lastPos = SOME lastPos, firstId, incDirs } =
    let
      val pos = SOME (#1 lastPos, ~1) (* EOF *)
    in
      (T.EOS, {streams = [], fileInfo, lastPos = pos, firstId, incDirs })
    end
    | getToken { streams = [], fileInfo, lastPos = NONE, firstId, incDirs } =
        (T.EOS, { streams = [], fileInfo,
            lastPos = SOME (firstId, ~1), firstId, incDirs })

  and handleInclude (stream: t) =
  let
    val (tk, streamNew) = getToken stream

    fun die () =
      prepLastTkError streamNew
        "#include with macro argument is not implemented"
  in
    case tk of
      T.StringConst path => includeFile streamNew path true
    | T.EOS => die ()
    | tk =>
        if String.sub (T.token2str tk, 0) = #"<" then
          let
            val (path, stream) = tryCollect stream
          in
            case path of
              SOME path => includeFile stream path false
            | NONE => die ()
          end
        else
          die ()
  end

  and includeFile stream fname localhdr =
  let
    val (fname, instream) = findPath stream fname localhdr
        handle EmptyPath =>
            prepLastTkError stream "#include path can not be empty"
    val newStream = T.S.createFromInstream fname instream
    val newFileInfo = T.S.convert newStream
  in
    getToken {
      streams = newStream :: #streams stream,
      fileInfo = newFileInfo :: #fileInfo stream,
      lastPos = #lastPos stream,
      firstId = #firstId stream,
      incDirs = #incDirs stream
    }
  end


  fun debugPrintToken cache tk (line, col) printLineRegardless =
  let
    val ` = Int.toString
  in
    if printLineRegardless orelse T.S.pposCacheGetLine cache <> line then
      print $ "\n" ^ T.S.pposCacheGetFname cache ^ ":" ^ `line ^ "\n\t"
    else
      ();
    print $ `col ^ ":" ^ T.token2str tk ^ "  "
  end

  fun adjustCacheStack (s as (top :: rest)) pos stream =
  let
    fun idMatches cache = T.S.pposCacheGetId cache = #1 pos
    fun metBefore [] = NONE
      | metBefore (c :: cs) =
        if idMatches c then
          SOME (c :: cs)
        else
          metBefore cs
  in
    if idMatches top then
      (false, s)
    else
      (true, case metBefore rest of
        NONE => T.S.pposCacheInit (getTopFileInfo stream) :: s
      | SOME stack => stack)
  end
    | adjustCacheStack _ _ _ = raise Unreachable

  fun debugPrint' cacheStack stream first =
    let
      val (tk, stream) = getToken stream
    in
      case tk of
        T.NewLine => debugPrint' cacheStack stream first
      | T.EOS => ()
      | tk =>
        let
          val pos = getLastPos stream
          val (stackChanged, cacheStack) =
                adjustCacheStack cacheStack pos stream

          val oldTop = hd cacheStack
          val (pair, top) = T.S.pposCacheAdvance pos oldTop
        in
          debugPrintToken oldTop tk pair (first orelse stackChanged);
          debugPrint' (top :: tl cacheStack) stream false
        end
    end

  fun debugPrint stream =
  let
    val cache = T.S.pposCacheInit $ hd $ #fileInfo stream
  in
    debugPrint' [cache] stream true;
    print "\n"
  end
end