stdray

Basic Parser

Mar 20th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. #pragma indent
  2. using Nemerle;
  3. using Nemerle.Collections;
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using NLocation = Nemerle.Compiler.Location;
  9. using Nemerle.Peg;
  10. using Nemerle.Compiler;
  11.  
  12. namespace YobaBasic.Macro
  13.     public abstract class LocatedParser
  14.         _location : NLocation
  15.         _lineOffsetMap : array[int]
  16.  
  17.         public this(location : NLocation, text : string)
  18.             _location = location
  19.             def fillLineOffsetMap()
  20.                 def map = List(text.Length / 10)
  21.                 map.Add(0)
  22.                 for (mutable i = 0; i < text.Length; i++)
  23.                     if (text[i] == '\n')
  24.                         map.Add(i + 1);
  25.                     else
  26.                         when (text[i] == '\r')
  27.                             def next = i + 1
  28.                             when (next < text.Length && text[next] != '\n')
  29.                                 map.Add(i + 1)
  30.                 map.ToArray()
  31.             _lineOffsetMap = fillLineOffsetMap()
  32.  
  33.         public ToLocation(startPos : int, endPos : int) : NLocation
  34.             def getTextPoint(pos : int) : TextPoint
  35.                 def result = _lineOffsetMap.BinarySearch(e => e - pos)
  36.                 def index = if (result < 0) (~result) - 1 else result
  37.                 def offset = _lineOffsetMap[index]
  38.                 def ch = pos - offset
  39.                 TextPoint(index + 1, ch + 1)
  40.             NLocation(_location.FileIndex,
  41.                       _location.Begin.Offcet <| getTextPoint <| startPos,
  42.                       _location.Begin.Offcet <| getTextPoint <| endPos)
  43.  
  44.         public ToLocation(tok : NToken) : NLocation
  45.             ToLocation(tok.StartPos, tok.EndPos)
Advertisement
Add Comment
Please, Sign In to add comment