lexer.nim 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This scanner is handwritten for efficiency. I used an elegant buffering
  10. # scheme which I have not seen anywhere else:
  11. # We guarantee that a whole line is in the buffer. Thus only when scanning
  12. # the \n or \r character we have to check wether we need to read in the next
  13. # chunk. (\n or \r already need special handling for incrementing the line
  14. # counter; choosing both \n and \r allows the scanner to properly read Unix,
  15. # DOS or Macintosh text files, even when it is not the native format.
  16. import
  17. hashes, options, msgs, strutils, platform, idents, nimlexbase, llstream,
  18. wordrecg, lineinfos, pathutils
  19. const
  20. MaxLineLength* = 80 # lines longer than this lead to a warning
  21. numChars*: set[char] = {'0'..'9', 'a'..'z', 'A'..'Z'}
  22. SymChars*: set[char] = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF'}
  23. SymStartChars*: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
  24. OpChars*: set[char] = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', '.',
  25. '|', '=', '%', '&', '$', '@', '~', ':'}
  26. # don't forget to update the 'highlite' module if these charsets should change
  27. type
  28. TTokType* = enum
  29. tkInvalid, tkEof, # order is important here!
  30. tkSymbol, # keywords:
  31. tkAddr, tkAnd, tkAs, tkAsm,
  32. tkBind, tkBlock, tkBreak, tkCase, tkCast,
  33. tkConcept, tkConst, tkContinue, tkConverter,
  34. tkDefer, tkDiscard, tkDistinct, tkDiv, tkDo,
  35. tkElif, tkElse, tkEnd, tkEnum, tkExcept, tkExport,
  36. tkFinally, tkFor, tkFrom, tkFunc,
  37. tkIf, tkImport, tkIn, tkInclude, tkInterface,
  38. tkIs, tkIsnot, tkIterator,
  39. tkLet,
  40. tkMacro, tkMethod, tkMixin, tkMod, tkNil, tkNot, tkNotin,
  41. tkObject, tkOf, tkOr, tkOut,
  42. tkProc, tkPtr, tkRaise, tkRef, tkReturn,
  43. tkShl, tkShr, tkStatic,
  44. tkTemplate,
  45. tkTry, tkTuple, tkType, tkUsing,
  46. tkVar, tkWhen, tkWhile, tkXor,
  47. tkYield, # end of keywords
  48. tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit,
  49. tkUIntLit, tkUInt8Lit, tkUInt16Lit, tkUInt32Lit, tkUInt64Lit,
  50. tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit,
  51. tkStrLit, tkRStrLit, tkTripleStrLit,
  52. tkGStrLit, tkGTripleStrLit, tkCharLit, tkParLe, tkParRi, tkBracketLe,
  53. tkBracketRi, tkCurlyLe, tkCurlyRi,
  54. tkBracketDotLe, tkBracketDotRi, # [. and .]
  55. tkCurlyDotLe, tkCurlyDotRi, # {. and .}
  56. tkParDotLe, tkParDotRi, # (. and .)
  57. tkComma, tkSemiColon,
  58. tkColon, tkColonColon, tkEquals, tkDot, tkDotDot, tkBracketLeColon,
  59. tkOpr, tkComment, tkAccent,
  60. tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr
  61. TTokTypes* = set[TTokType]
  62. const
  63. weakTokens = {tkComma, tkSemiColon, tkColon,
  64. tkParRi, tkParDotRi, tkBracketRi, tkBracketDotRi,
  65. tkCurlyRi} # \
  66. # tokens that should not be considered for previousToken
  67. tokKeywordLow* = succ(tkSymbol)
  68. tokKeywordHigh* = pred(tkIntLit)
  69. TokTypeToStr*: array[TTokType, string] = ["tkInvalid", "[EOF]",
  70. "tkSymbol",
  71. "addr", "and", "as", "asm",
  72. "bind", "block", "break", "case", "cast",
  73. "concept", "const", "continue", "converter",
  74. "defer", "discard", "distinct", "div", "do",
  75. "elif", "else", "end", "enum", "except", "export",
  76. "finally", "for", "from", "func", "if",
  77. "import", "in", "include", "interface", "is", "isnot", "iterator",
  78. "let",
  79. "macro", "method", "mixin", "mod",
  80. "nil", "not", "notin", "object", "of", "or",
  81. "out", "proc", "ptr", "raise", "ref", "return",
  82. "shl", "shr", "static",
  83. "template",
  84. "try", "tuple", "type", "using",
  85. "var", "when", "while", "xor",
  86. "yield",
  87. "tkIntLit", "tkInt8Lit", "tkInt16Lit", "tkInt32Lit", "tkInt64Lit",
  88. "tkUIntLit", "tkUInt8Lit", "tkUInt16Lit", "tkUInt32Lit", "tkUInt64Lit",
  89. "tkFloatLit", "tkFloat32Lit", "tkFloat64Lit", "tkFloat128Lit",
  90. "tkStrLit", "tkRStrLit",
  91. "tkTripleStrLit", "tkGStrLit", "tkGTripleStrLit", "tkCharLit", "(",
  92. ")", "[", "]", "{", "}", "[.", ".]", "{.", ".}", "(.", ".)",
  93. ",", ";",
  94. ":", "::", "=", ".", "..", "[:",
  95. "tkOpr", "tkComment", "`",
  96. "tkSpaces", "tkInfixOpr",
  97. "tkPrefixOpr", "tkPostfixOpr"]
  98. type
  99. TNumericalBase* = enum
  100. base10, # base10 is listed as the first element,
  101. # so that it is the correct default value
  102. base2, base8, base16
  103. CursorPosition* {.pure.} = enum ## XXX remove this again
  104. None, InToken, BeforeToken, AfterToken
  105. TToken* = object # a Nim token
  106. tokType*: TTokType # the type of the token
  107. indent*: int # the indentation; != -1 if the token has been
  108. # preceded with indentation
  109. ident*: PIdent # the parsed identifier
  110. iNumber*: BiggestInt # the parsed integer literal
  111. fNumber*: BiggestFloat # the parsed floating point literal
  112. base*: TNumericalBase # the numerical base; only valid for int
  113. # or float literals
  114. strongSpaceA*: int8 # leading spaces of an operator
  115. strongSpaceB*: int8 # trailing spaces of an operator
  116. literal*: string # the parsed (string) literal; and
  117. # documentation comments are here too
  118. line*, col*: int
  119. when defined(nimpretty):
  120. offsetA*, offsetB*: int # used for pretty printing so that literals
  121. # like 0b01 or r"\L" are unaffected
  122. commentOffsetA*, commentOffsetB*: int
  123. TErrorHandler* = proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string)
  124. TLexer* = object of TBaseLexer
  125. fileIdx*: FileIndex
  126. indentAhead*: int # if > 0 an indendation has already been read
  127. # this is needed because scanning comments
  128. # needs so much look-ahead
  129. currLineIndent*: int
  130. strongSpaces*, allowTabs*: bool
  131. cursor*: CursorPosition
  132. errorHandler*: TErrorHandler
  133. cache*: IdentCache
  134. when defined(nimsuggest):
  135. previousToken: TLineInfo
  136. config*: ConfigRef
  137. when defined(nimpretty):
  138. var
  139. gIndentationWidth*: int
  140. proc getLineInfo*(L: TLexer, tok: TToken): TLineInfo {.inline.} =
  141. result = newLineInfo(L.fileIdx, tok.line, tok.col)
  142. when defined(nimpretty):
  143. result.offsetA = tok.offsetA
  144. result.offsetB = tok.offsetB
  145. result.commentOffsetA = tok.commentOffsetA
  146. result.commentOffsetB = tok.commentOffsetB
  147. proc isKeyword*(kind: TTokType): bool =
  148. result = (kind >= tokKeywordLow) and (kind <= tokKeywordHigh)
  149. template ones(n): untyped = ((1 shl n)-1) # for utf-8 conversion
  150. proc isNimIdentifier*(s: string): bool =
  151. let sLen = s.len
  152. if sLen > 0 and s[0] in SymStartChars:
  153. var i = 1
  154. while i < sLen:
  155. if s[i] == '_': inc(i)
  156. if i < sLen and s[i] notin SymChars: return
  157. inc(i)
  158. result = true
  159. proc tokToStr*(tok: TToken): string =
  160. case tok.tokType
  161. of tkIntLit..tkInt64Lit: result = $tok.iNumber
  162. of tkFloatLit..tkFloat64Lit: result = $tok.fNumber
  163. of tkInvalid, tkStrLit..tkCharLit, tkComment: result = tok.literal
  164. of tkParLe..tkColon, tkEof, tkAccent:
  165. result = TokTypeToStr[tok.tokType]
  166. else:
  167. if tok.ident != nil:
  168. result = tok.ident.s
  169. else:
  170. result = ""
  171. proc prettyTok*(tok: TToken): string =
  172. if isKeyword(tok.tokType): result = "keyword " & tok.ident.s
  173. else: result = tokToStr(tok)
  174. proc printTok*(conf: ConfigRef; tok: TToken) =
  175. msgWriteln(conf, $tok.line & ":" & $tok.col & "\t" &
  176. TokTypeToStr[tok.tokType] & " " & tokToStr(tok))
  177. proc initToken*(L: var TToken) =
  178. L.tokType = tkInvalid
  179. L.iNumber = 0
  180. L.indent = 0
  181. L.strongSpaceA = 0
  182. L.literal = ""
  183. L.fNumber = 0.0
  184. L.base = base10
  185. L.ident = nil
  186. when defined(nimpretty):
  187. L.commentOffsetA = 0
  188. L.commentOffsetB = 0
  189. proc fillToken(L: var TToken) =
  190. L.tokType = tkInvalid
  191. L.iNumber = 0
  192. L.indent = 0
  193. L.strongSpaceA = 0
  194. setLen(L.literal, 0)
  195. L.fNumber = 0.0
  196. L.base = base10
  197. L.ident = nil
  198. when defined(nimpretty):
  199. L.commentOffsetA = 0
  200. L.commentOffsetB = 0
  201. proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
  202. cache: IdentCache; config: ConfigRef) =
  203. openBaseLexer(lex, inputstream)
  204. lex.fileIdx = fileidx
  205. lex.indentAhead = - 1
  206. lex.currLineIndent = 0
  207. inc(lex.lineNumber, inputstream.lineOffset)
  208. lex.cache = cache
  209. when defined(nimsuggest):
  210. lex.previousToken.fileIndex = fileIdx
  211. lex.config = config
  212. proc openLexer*(lex: var TLexer, filename: AbsoluteFile, inputstream: PLLStream;
  213. cache: IdentCache; config: ConfigRef) =
  214. openLexer(lex, fileInfoIdx(config, filename), inputstream, cache, config)
  215. proc closeLexer*(lex: var TLexer) =
  216. if lex.config != nil:
  217. inc(lex.config.linesCompiled, lex.lineNumber)
  218. closeBaseLexer(lex)
  219. proc getLineInfo(L: TLexer): TLineInfo =
  220. result = newLineInfo(L.fileIdx, L.lineNumber, getColNumber(L, L.bufpos))
  221. proc dispMessage(L: TLexer; info: TLineInfo; msg: TMsgKind; arg: string) =
  222. if L.errorHandler.isNil:
  223. msgs.message(L.config, info, msg, arg)
  224. else:
  225. L.errorHandler(L.config, info, msg, arg)
  226. proc lexMessage*(L: TLexer, msg: TMsgKind, arg = "") =
  227. L.dispMessage(getLineInfo(L), msg, arg)
  228. proc lexMessageTok*(L: TLexer, msg: TMsgKind, tok: TToken, arg = "") =
  229. var info = newLineInfo(L.fileIdx, tok.line, tok.col)
  230. L.dispMessage(info, msg, arg)
  231. proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") =
  232. var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart)
  233. L.dispMessage(info, msg, arg)
  234. proc matchTwoChars(L: TLexer, first: char, second: set[char]): bool =
  235. result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second)
  236. template tokenBegin(tok, pos) {.dirty.} =
  237. when defined(nimsuggest):
  238. var colA = getColNumber(L, pos)
  239. when defined(nimpretty):
  240. tok.offsetA = L.offsetBase + pos
  241. template tokenEnd(tok, pos) {.dirty.} =
  242. when defined(nimsuggest):
  243. let colB = getColNumber(L, pos)+1
  244. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  245. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  246. L.cursor = CursorPosition.InToken
  247. L.config.m.trackPos.col = colA.int16
  248. colA = 0
  249. when defined(nimpretty):
  250. tok.offsetB = L.offsetBase + pos
  251. template tokenEndIgnore(tok, pos) =
  252. when defined(nimsuggest):
  253. let colB = getColNumber(L, pos)
  254. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  255. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  256. L.config.m.trackPos.fileIndex = trackPosInvalidFileIdx
  257. L.config.m.trackPos.line = 0'u16
  258. colA = 0
  259. when defined(nimpretty):
  260. tok.offsetB = L.offsetBase + pos
  261. template tokenEndPrevious(tok, pos) =
  262. when defined(nimsuggest):
  263. # when we detect the cursor in whitespace, we attach the track position
  264. # to the token that came before that, but only if we haven't detected
  265. # the cursor in a string literal or comment:
  266. let colB = getColNumber(L, pos)
  267. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  268. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  269. L.cursor = CursorPosition.BeforeToken
  270. L.config.m.trackPos = L.previousToken
  271. L.config.m.trackPosAttached = true
  272. colA = 0
  273. when defined(nimpretty):
  274. tok.offsetB = L.offsetBase + pos
  275. {.push overflowChecks: off.}
  276. # We need to parse the largest uint literal without overflow checks
  277. proc unsafeParseUInt(s: string, b: var BiggestInt, start = 0): int =
  278. var i = start
  279. if i < s.len and s[i] in {'0'..'9'}:
  280. b = 0
  281. while i < s.len and s[i] in {'0'..'9'}:
  282. b = b * 10 + (ord(s[i]) - ord('0'))
  283. inc(i)
  284. while i < s.len and s[i] == '_': inc(i) # underscores are allowed and ignored
  285. result = i - start
  286. {.pop.} # overflowChecks
  287. template eatChar(L: var TLexer, t: var TToken, replacementChar: char) =
  288. add(t.literal, replacementChar)
  289. inc(L.bufpos)
  290. template eatChar(L: var TLexer, t: var TToken) =
  291. add(t.literal, L.buf[L.bufpos])
  292. inc(L.bufpos)
  293. proc getNumber(L: var TLexer, result: var TToken) =
  294. proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]): Natural =
  295. var pos = L.bufpos # use registers for pos, buf
  296. var buf = L.buf
  297. result = 0
  298. while true:
  299. if buf[pos] in chars:
  300. add(tok.literal, buf[pos])
  301. inc(pos)
  302. inc(result)
  303. else:
  304. break
  305. if buf[pos] == '_':
  306. if buf[pos+1] notin chars:
  307. lexMessage(L, errGenerated,
  308. "only single underscores may occur in a token and token may not " &
  309. "end with an underscore: e.g. '1__1' and '1_' are invalid")
  310. break
  311. add(tok.literal, '_')
  312. inc(pos)
  313. L.bufpos = pos
  314. proc matchChars(L: var TLexer, tok: var TToken, chars: set[char]) =
  315. var pos = L.bufpos # use registers for pos, buf
  316. var buf = L.buf
  317. while buf[pos] in chars:
  318. add(tok.literal, buf[pos])
  319. inc(pos)
  320. L.bufpos = pos
  321. proc lexMessageLitNum(L: var TLexer, msg: string, startpos: int, msgKind = errGenerated) =
  322. # Used to get slightly human friendlier err messages.
  323. const literalishChars = {'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', 'O',
  324. 'c', 'C', 'b', 'B', '_', '.', '\'', 'd', 'i', 'u'}
  325. var msgPos = L.bufpos
  326. var t: TToken
  327. t.literal = ""
  328. L.bufpos = startpos # Use L.bufpos as pos because of matchChars
  329. matchChars(L, t, literalishChars)
  330. # We must verify +/- specifically so that we're not past the literal
  331. if L.buf[L.bufpos] in {'+', '-'} and
  332. L.buf[L.bufpos - 1] in {'e', 'E'}:
  333. add(t.literal, L.buf[L.bufpos])
  334. inc(L.bufpos)
  335. matchChars(L, t, literalishChars)
  336. if L.buf[L.bufpos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}:
  337. inc(L.bufpos)
  338. add(t.literal, L.buf[L.bufpos])
  339. matchChars(L, t, {'0'..'9'})
  340. L.bufpos = msgPos
  341. lexMessage(L, msgKind, msg % t.literal)
  342. var
  343. startpos, endpos: int
  344. xi: BiggestInt
  345. isBase10 = true
  346. numDigits = 0
  347. const
  348. # 'c', 'C' is deprecated
  349. baseCodeChars = {'X', 'x', 'o', 'b', 'B', 'c', 'C'}
  350. literalishChars = baseCodeChars + {'A'..'F', 'a'..'f', '0'..'9', '_', '\''}
  351. floatTypes = {tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit}
  352. result.tokType = tkIntLit # int literal until we know better
  353. result.literal = ""
  354. result.base = base10
  355. startpos = L.bufpos
  356. tokenBegin(result, startPos)
  357. # First stage: find out base, make verifications, build token literal string
  358. # {'c', 'C'} is added for deprecation reasons to provide a clear error message
  359. if L.buf[L.bufpos] == '0' and L.buf[L.bufpos + 1] in baseCodeChars + {'c', 'C', 'O'}:
  360. isBase10 = false
  361. eatChar(L, result, '0')
  362. case L.buf[L.bufpos]
  363. of 'c', 'C':
  364. lexMessageLitNum(L,
  365. "$1 will soon be invalid for oct literals; Use '0o' " &
  366. "for octals. 'c', 'C' prefix",
  367. startpos,
  368. warnDeprecated)
  369. eatChar(L, result, 'c')
  370. numDigits = matchUnderscoreChars(L, result, {'0'..'7'})
  371. of 'O':
  372. lexMessageLitNum(L, "$1 is an invalid int literal; For octal literals " &
  373. "use the '0o' prefix.", startpos)
  374. of 'x', 'X':
  375. eatChar(L, result, 'x')
  376. numDigits = matchUnderscoreChars(L, result, {'0'..'9', 'a'..'f', 'A'..'F'})
  377. of 'o':
  378. eatChar(L, result, 'o')
  379. numDigits = matchUnderscoreChars(L, result, {'0'..'7'})
  380. of 'b', 'B':
  381. eatChar(L, result, 'b')
  382. numDigits = matchUnderscoreChars(L, result, {'0'..'1'})
  383. else:
  384. internalError(L.config, getLineInfo(L), "getNumber")
  385. if numDigits == 0:
  386. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  387. else:
  388. discard matchUnderscoreChars(L, result, {'0'..'9'})
  389. if (L.buf[L.bufpos] == '.') and (L.buf[L.bufpos + 1] in {'0'..'9'}):
  390. result.tokType = tkFloatLit
  391. eatChar(L, result, '.')
  392. discard matchUnderscoreChars(L, result, {'0'..'9'})
  393. if L.buf[L.bufpos] in {'e', 'E'}:
  394. result.tokType = tkFloatLit
  395. eatChar(L, result, 'e')
  396. if L.buf[L.bufpos] in {'+', '-'}:
  397. eatChar(L, result)
  398. discard matchUnderscoreChars(L, result, {'0'..'9'})
  399. endpos = L.bufpos
  400. # Second stage, find out if there's a datatype suffix and handle it
  401. var postPos = endpos
  402. if L.buf[postPos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}:
  403. if L.buf[postPos] == '\'':
  404. inc(postPos)
  405. case L.buf[postPos]
  406. of 'f', 'F':
  407. inc(postPos)
  408. if (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  409. result.tokType = tkFloat32Lit
  410. inc(postPos, 2)
  411. elif (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  412. result.tokType = tkFloat64Lit
  413. inc(postPos, 2)
  414. elif (L.buf[postPos] == '1') and
  415. (L.buf[postPos + 1] == '2') and
  416. (L.buf[postPos + 2] == '8'):
  417. result.tokType = tkFloat128Lit
  418. inc(postPos, 3)
  419. else: # "f" alone defaults to float32
  420. result.tokType = tkFloat32Lit
  421. of 'd', 'D': # ad hoc convenience shortcut for f64
  422. inc(postPos)
  423. result.tokType = tkFloat64Lit
  424. of 'i', 'I':
  425. inc(postPos)
  426. if (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  427. result.tokType = tkInt64Lit
  428. inc(postPos, 2)
  429. elif (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  430. result.tokType = tkInt32Lit
  431. inc(postPos, 2)
  432. elif (L.buf[postPos] == '1') and (L.buf[postPos + 1] == '6'):
  433. result.tokType = tkInt16Lit
  434. inc(postPos, 2)
  435. elif (L.buf[postPos] == '8'):
  436. result.tokType = tkInt8Lit
  437. inc(postPos)
  438. else:
  439. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  440. of 'u', 'U':
  441. inc(postPos)
  442. if (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  443. result.tokType = tkUInt64Lit
  444. inc(postPos, 2)
  445. elif (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  446. result.tokType = tkUInt32Lit
  447. inc(postPos, 2)
  448. elif (L.buf[postPos] == '1') and (L.buf[postPos + 1] == '6'):
  449. result.tokType = tkUInt16Lit
  450. inc(postPos, 2)
  451. elif (L.buf[postPos] == '8'):
  452. result.tokType = tkUInt8Lit
  453. inc(postPos)
  454. else:
  455. result.tokType = tkUIntLit
  456. else:
  457. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  458. # Is there still a literalish char awaiting? Then it's an error!
  459. if L.buf[postPos] in literalishChars or
  460. (L.buf[postPos] == '.' and L.buf[postPos + 1] in {'0'..'9'}):
  461. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  462. # Third stage, extract actual number
  463. L.bufpos = startpos # restore position
  464. var pos: int = startpos
  465. try:
  466. if (L.buf[pos] == '0') and (L.buf[pos + 1] in baseCodeChars):
  467. inc(pos, 2)
  468. xi = 0 # it is a base prefix
  469. case L.buf[pos - 1]
  470. of 'b', 'B':
  471. result.base = base2
  472. while pos < endpos:
  473. if L.buf[pos] != '_':
  474. xi = `shl`(xi, 1) or (ord(L.buf[pos]) - ord('0'))
  475. inc(pos)
  476. # 'c', 'C' is deprecated
  477. of 'o', 'c', 'C':
  478. result.base = base8
  479. while pos < endpos:
  480. if L.buf[pos] != '_':
  481. xi = `shl`(xi, 3) or (ord(L.buf[pos]) - ord('0'))
  482. inc(pos)
  483. of 'x', 'X':
  484. result.base = base16
  485. while pos < endpos:
  486. case L.buf[pos]
  487. of '_':
  488. inc(pos)
  489. of '0'..'9':
  490. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('0'))
  491. inc(pos)
  492. of 'a'..'f':
  493. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('a') + 10)
  494. inc(pos)
  495. of 'A'..'F':
  496. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('A') + 10)
  497. inc(pos)
  498. else:
  499. break
  500. else:
  501. internalError(L.config, getLineInfo(L), "getNumber")
  502. case result.tokType
  503. of tkIntLit, tkInt64Lit: result.iNumber = xi
  504. of tkInt8Lit: result.iNumber = BiggestInt(int8(toU8(int(xi))))
  505. of tkInt16Lit: result.iNumber = BiggestInt(int16(toU16(int(xi))))
  506. of tkInt32Lit: result.iNumber = BiggestInt(int32(toU32(int64(xi))))
  507. of tkUIntLit, tkUInt64Lit: result.iNumber = xi
  508. of tkUInt8Lit: result.iNumber = BiggestInt(uint8(toU8(int(xi))))
  509. of tkUInt16Lit: result.iNumber = BiggestInt(uint16(toU16(int(xi))))
  510. of tkUInt32Lit: result.iNumber = BiggestInt(uint32(toU32(int64(xi))))
  511. of tkFloat32Lit:
  512. result.fNumber = (cast[PFloat32](addr(xi)))[]
  513. # note: this code is endian neutral!
  514. # XXX: Test this on big endian machine!
  515. of tkFloat64Lit, tkFloatLit:
  516. result.fNumber = (cast[PFloat64](addr(xi)))[]
  517. else: internalError(L.config, getLineInfo(L), "getNumber")
  518. # Bounds checks. Non decimal literals are allowed to overflow the range of
  519. # the datatype as long as their pattern don't overflow _bitwise_, hence
  520. # below checks of signed sizes against uint*.high is deliberate:
  521. # (0x80'u8 = 128, 0x80'i8 = -128, etc == OK)
  522. if result.tokType notin floatTypes:
  523. let outOfRange = case result.tokType:
  524. of tkUInt8Lit, tkUInt16Lit, tkUInt32Lit: result.iNumber != xi
  525. of tkInt8Lit: (xi > BiggestInt(uint8.high))
  526. of tkInt16Lit: (xi > BiggestInt(uint16.high))
  527. of tkInt32Lit: (xi > BiggestInt(uint32.high))
  528. else: false
  529. if outOfRange:
  530. #echo "out of range num: ", result.iNumber, " vs ", xi
  531. lexMessageLitNum(L, "number out of range: '$1'", startpos)
  532. else:
  533. case result.tokType
  534. of floatTypes:
  535. result.fNumber = parseFloat(result.literal)
  536. of tkUint64Lit:
  537. xi = 0
  538. let len = unsafeParseUInt(result.literal, xi)
  539. if len != result.literal.len or len == 0:
  540. raise newException(ValueError, "invalid integer: " & $xi)
  541. result.iNumber = xi
  542. else:
  543. result.iNumber = parseBiggestInt(result.literal)
  544. # Explicit bounds checks
  545. let outOfRange =
  546. case result.tokType
  547. of tkInt8Lit: (result.iNumber < int8.low or result.iNumber > int8.high)
  548. of tkUInt8Lit: (result.iNumber < BiggestInt(uint8.low) or
  549. result.iNumber > BiggestInt(uint8.high))
  550. of tkInt16Lit: (result.iNumber < int16.low or result.iNumber > int16.high)
  551. of tkUInt16Lit: (result.iNumber < BiggestInt(uint16.low) or
  552. result.iNumber > BiggestInt(uint16.high))
  553. of tkInt32Lit: (result.iNumber < int32.low or result.iNumber > int32.high)
  554. of tkUInt32Lit: (result.iNumber < BiggestInt(uint32.low) or
  555. result.iNumber > BiggestInt(uint32.high))
  556. else: false
  557. if outOfRange: lexMessageLitNum(L, "number out of range: '$1'", startpos)
  558. # Promote int literal to int64? Not always necessary, but more consistent
  559. if result.tokType == tkIntLit:
  560. if (result.iNumber < low(int32)) or (result.iNumber > high(int32)):
  561. result.tokType = tkInt64Lit
  562. except ValueError:
  563. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  564. except OverflowError, RangeError:
  565. lexMessageLitNum(L, "number out of range: '$1'", startpos)
  566. tokenEnd(result, postPos-1)
  567. L.bufpos = postPos
  568. proc handleHexChar(L: var TLexer, xi: var int) =
  569. case L.buf[L.bufpos]
  570. of '0'..'9':
  571. xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('0'))
  572. inc(L.bufpos)
  573. of 'a'..'f':
  574. xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('a') + 10)
  575. inc(L.bufpos)
  576. of 'A'..'F':
  577. xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('A') + 10)
  578. inc(L.bufpos)
  579. else: discard
  580. proc handleDecChars(L: var TLexer, xi: var int) =
  581. while L.buf[L.bufpos] in {'0'..'9'}:
  582. xi = (xi * 10) + (ord(L.buf[L.bufpos]) - ord('0'))
  583. inc(L.bufpos)
  584. proc getEscapedChar(L: var TLexer, tok: var TToken) =
  585. inc(L.bufpos) # skip '\'
  586. case L.buf[L.bufpos]
  587. of 'n', 'N':
  588. if L.config.oldNewlines:
  589. if tok.tokType == tkCharLit:
  590. lexMessage(L, errGenerated, "\\n not allowed in character literal")
  591. add(tok.literal, L.config.target.tnl)
  592. else:
  593. add(tok.literal, '\L')
  594. inc(L.bufpos)
  595. of 'p', 'P':
  596. if tok.tokType == tkCharLit:
  597. lexMessage(L, errGenerated, "\\p not allowed in character literal")
  598. add(tok.literal, L.config.target.tnl)
  599. inc(L.bufpos)
  600. of 'r', 'R', 'c', 'C':
  601. add(tok.literal, CR)
  602. inc(L.bufpos)
  603. of 'l', 'L':
  604. add(tok.literal, LF)
  605. inc(L.bufpos)
  606. of 'f', 'F':
  607. add(tok.literal, FF)
  608. inc(L.bufpos)
  609. of 'e', 'E':
  610. add(tok.literal, ESC)
  611. inc(L.bufpos)
  612. of 'a', 'A':
  613. add(tok.literal, BEL)
  614. inc(L.bufpos)
  615. of 'b', 'B':
  616. add(tok.literal, BACKSPACE)
  617. inc(L.bufpos)
  618. of 'v', 'V':
  619. add(tok.literal, VT)
  620. inc(L.bufpos)
  621. of 't', 'T':
  622. add(tok.literal, '\t')
  623. inc(L.bufpos)
  624. of '\'', '\"':
  625. add(tok.literal, L.buf[L.bufpos])
  626. inc(L.bufpos)
  627. of '\\':
  628. add(tok.literal, '\\')
  629. inc(L.bufpos)
  630. of 'x', 'X', 'u', 'U':
  631. var tp = L.buf[L.bufpos]
  632. inc(L.bufpos)
  633. var xi = 0
  634. handleHexChar(L, xi)
  635. handleHexChar(L, xi)
  636. if tp in {'u', 'U'}:
  637. handleHexChar(L, xi)
  638. handleHexChar(L, xi)
  639. # inlined toUTF-8 to avoid unicode and strutils dependencies.
  640. if xi <=% 127:
  641. add(tok.literal, xi.char )
  642. elif xi <=% 0x07FF:
  643. add(tok.literal, ((xi shr 6) or 0b110_00000).char )
  644. add(tok.literal, ((xi and ones(6)) or 0b10_0000_00).char )
  645. elif xi <=% 0xFFFF:
  646. add(tok.literal, (xi shr 12 or 0b1110_0000).char )
  647. add(tok.literal, (xi shr 6 and ones(6) or 0b10_0000_00).char )
  648. add(tok.literal, (xi and ones(6) or 0b10_0000_00).char )
  649. else: # value is 0xFFFF
  650. add(tok.literal, "\xef\xbf\xbf" )
  651. else:
  652. add(tok.literal, chr(xi))
  653. of '0'..'9':
  654. if matchTwoChars(L, '0', {'0'..'9'}):
  655. lexMessage(L, warnOctalEscape)
  656. var xi = 0
  657. handleDecChars(L, xi)
  658. if (xi <= 255): add(tok.literal, chr(xi))
  659. else: lexMessage(L, errGenerated, "invalid character constant")
  660. else: lexMessage(L, errGenerated, "invalid character constant")
  661. proc newString(s: cstring, len: int): string =
  662. ## XXX, how come there is no support for this?
  663. result = newString(len)
  664. for i in 0 ..< len:
  665. result[i] = s[i]
  666. proc handleCRLF(L: var TLexer, pos: int): int =
  667. template registerLine =
  668. let col = L.getColNumber(pos)
  669. if col > MaxLineLength:
  670. lexMessagePos(L, hintLineTooLong, pos)
  671. case L.buf[pos]
  672. of CR:
  673. registerLine()
  674. result = nimlexbase.handleCR(L, pos)
  675. of LF:
  676. registerLine()
  677. result = nimlexbase.handleLF(L, pos)
  678. else: result = pos
  679. proc getString(L: var TLexer, tok: var TToken, rawMode: bool) =
  680. var pos = L.bufpos
  681. var buf = L.buf # put `buf` in a register
  682. var line = L.lineNumber # save linenumber for better error message
  683. tokenBegin(tok, pos)
  684. inc pos # skip "
  685. if buf[pos] == '\"' and buf[pos+1] == '\"':
  686. tok.tokType = tkTripleStrLit # long string literal:
  687. inc(pos, 2) # skip ""
  688. # skip leading newline:
  689. if buf[pos] in {' ', '\t'}:
  690. var newpos = pos+1
  691. while buf[newpos] in {' ', '\t'}: inc newpos
  692. if buf[newpos] in {CR, LF}: pos = newpos
  693. pos = handleCRLF(L, pos)
  694. buf = L.buf
  695. while true:
  696. case buf[pos]
  697. of '\"':
  698. if buf[pos+1] == '\"' and buf[pos+2] == '\"' and
  699. buf[pos+3] != '\"':
  700. tokenEndIgnore(tok, pos+2)
  701. L.bufpos = pos + 3 # skip the three """
  702. break
  703. add(tok.literal, '\"')
  704. inc(pos)
  705. of CR, LF:
  706. tokenEndIgnore(tok, pos)
  707. pos = handleCRLF(L, pos)
  708. buf = L.buf
  709. add(tok.literal, "\n")
  710. of nimlexbase.EndOfFile:
  711. tokenEndIgnore(tok, pos)
  712. var line2 = L.lineNumber
  713. L.lineNumber = line
  714. lexMessagePos(L, errGenerated, L.lineStart, "closing \"\"\" expected, but end of file reached")
  715. L.lineNumber = line2
  716. L.bufpos = pos
  717. break
  718. else:
  719. add(tok.literal, buf[pos])
  720. inc(pos)
  721. else:
  722. # ordinary string literal
  723. if rawMode: tok.tokType = tkRStrLit
  724. else: tok.tokType = tkStrLit
  725. while true:
  726. var c = buf[pos]
  727. if c == '\"':
  728. if rawMode and buf[pos+1] == '\"':
  729. inc(pos, 2)
  730. add(tok.literal, '"')
  731. else:
  732. tokenEndIgnore(tok, pos)
  733. inc(pos) # skip '"'
  734. break
  735. elif c in {CR, LF, nimlexbase.EndOfFile}:
  736. tokenEndIgnore(tok, pos)
  737. lexMessage(L, errGenerated, "closing \" expected")
  738. break
  739. elif (c == '\\') and not rawMode:
  740. L.bufpos = pos
  741. getEscapedChar(L, tok)
  742. pos = L.bufpos
  743. else:
  744. add(tok.literal, c)
  745. inc(pos)
  746. L.bufpos = pos
  747. proc getCharacter(L: var TLexer, tok: var TToken) =
  748. tokenBegin(tok, L.bufpos)
  749. inc(L.bufpos) # skip '
  750. var c = L.buf[L.bufpos]
  751. case c
  752. of '\0'..pred(' '), '\'': lexMessage(L, errGenerated, "invalid character literal")
  753. of '\\': getEscapedChar(L, tok)
  754. else:
  755. tok.literal = $c
  756. inc(L.bufpos)
  757. if L.buf[L.bufpos] != '\'':
  758. lexMessage(L, errGenerated, "missing closing ' for character literal")
  759. tokenEndIgnore(tok, L.bufpos)
  760. inc(L.bufpos) # skip '
  761. proc getSymbol(L: var TLexer, tok: var TToken) =
  762. var h: Hash = 0
  763. var pos = L.bufpos
  764. var buf = L.buf
  765. tokenBegin(tok, pos)
  766. while true:
  767. var c = buf[pos]
  768. case c
  769. of 'a'..'z', '0'..'9', '\x80'..'\xFF':
  770. h = h !& ord(c)
  771. inc(pos)
  772. of 'A'..'Z':
  773. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  774. h = h !& ord(c)
  775. inc(pos)
  776. of '_':
  777. if buf[pos+1] notin SymChars:
  778. lexMessage(L, errGenerated, "invalid token: trailing underscore")
  779. break
  780. inc(pos)
  781. else: break
  782. tokenEnd(tok, pos-1)
  783. h = !$h
  784. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  785. L.bufpos = pos
  786. if (tok.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
  787. (tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
  788. tok.tokType = tkSymbol
  789. else:
  790. tok.tokType = TTokType(tok.ident.id + ord(tkSymbol))
  791. proc endOperator(L: var TLexer, tok: var TToken, pos: int,
  792. hash: Hash) {.inline.} =
  793. var h = !$hash
  794. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  795. if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr
  796. else: tok.tokType = TTokType(tok.ident.id - oprLow + ord(tkColon))
  797. L.bufpos = pos
  798. proc getOperator(L: var TLexer, tok: var TToken) =
  799. var pos = L.bufpos
  800. var buf = L.buf
  801. tokenBegin(tok, pos)
  802. var h: Hash = 0
  803. while true:
  804. var c = buf[pos]
  805. if c notin OpChars: break
  806. h = h !& ord(c)
  807. inc(pos)
  808. endOperator(L, tok, pos, h)
  809. tokenEnd(tok, pos-1)
  810. # advance pos but don't store it in L.bufpos so the next token (which might
  811. # be an operator too) gets the preceding spaces:
  812. tok.strongSpaceB = 0
  813. while buf[pos] == ' ':
  814. inc pos
  815. inc tok.strongSpaceB
  816. if buf[pos] in {CR, LF, nimlexbase.EndOfFile}:
  817. tok.strongSpaceB = -1
  818. proc getPrecedence*(tok: TToken, strongSpaces: bool): int =
  819. ## Calculates the precedence of the given token.
  820. template considerStrongSpaces(x): untyped =
  821. x + (if strongSpaces: 100 - tok.strongSpaceA.int*10 else: 0)
  822. case tok.tokType
  823. of tkOpr:
  824. let L = tok.ident.s.len
  825. let relevantChar = tok.ident.s[0]
  826. # arrow like?
  827. if L > 1 and tok.ident.s[L-1] == '>' and
  828. tok.ident.s[L-2] in {'-', '~', '='}: return considerStrongSpaces(1)
  829. template considerAsgn(value: untyped) =
  830. result = if tok.ident.s[L-1] == '=': 1 else: value
  831. case relevantChar
  832. of '$', '^': considerAsgn(10)
  833. of '*', '%', '/', '\\': considerAsgn(9)
  834. of '~': result = 8
  835. of '+', '-', '|': considerAsgn(8)
  836. of '&': considerAsgn(7)
  837. of '=', '<', '>', '!': result = 5
  838. of '.': considerAsgn(6)
  839. of '?': result = 2
  840. else: considerAsgn(2)
  841. of tkDiv, tkMod, tkShl, tkShr: result = 9
  842. of tkIn, tkNotin, tkIs, tkIsnot, tkNot, tkOf, tkAs: result = 5
  843. of tkDotDot: result = 6
  844. of tkAnd: result = 4
  845. of tkOr, tkXor, tkPtr, tkRef: result = 3
  846. else: return -10
  847. result = considerStrongSpaces(result)
  848. proc newlineFollows*(L: TLexer): bool =
  849. var pos = L.bufpos
  850. var buf = L.buf
  851. while true:
  852. case buf[pos]
  853. of ' ', '\t':
  854. inc(pos)
  855. of CR, LF:
  856. result = true
  857. break
  858. of '#':
  859. inc(pos)
  860. if buf[pos] == '#': inc(pos)
  861. if buf[pos] != '[': return true
  862. else:
  863. break
  864. proc skipMultiLineComment(L: var TLexer; tok: var TToken; start: int;
  865. isDoc: bool) =
  866. var pos = start
  867. var buf = L.buf
  868. var toStrip = 0
  869. tokenBegin(tok, pos)
  870. # detect the amount of indentation:
  871. if isDoc:
  872. toStrip = getColNumber(L, pos)
  873. while buf[pos] == ' ': inc pos
  874. if buf[pos] in {CR, LF}:
  875. pos = handleCRLF(L, pos)
  876. buf = L.buf
  877. toStrip = 0
  878. while buf[pos] == ' ':
  879. inc pos
  880. inc toStrip
  881. var nesting = 0
  882. while true:
  883. case buf[pos]
  884. of '#':
  885. if isDoc:
  886. if buf[pos+1] == '#' and buf[pos+2] == '[':
  887. inc nesting
  888. tok.literal.add '#'
  889. elif buf[pos+1] == '[':
  890. inc nesting
  891. inc pos
  892. of ']':
  893. if isDoc:
  894. if buf[pos+1] == '#' and buf[pos+2] == '#':
  895. if nesting == 0:
  896. tokenEndIgnore(tok, pos+2)
  897. inc(pos, 3)
  898. break
  899. dec nesting
  900. tok.literal.add ']'
  901. elif buf[pos+1] == '#':
  902. if nesting == 0:
  903. tokenEndIgnore(tok, pos+1)
  904. inc(pos, 2)
  905. break
  906. dec nesting
  907. inc pos
  908. of CR, LF:
  909. tokenEndIgnore(tok, pos)
  910. pos = handleCRLF(L, pos)
  911. buf = L.buf
  912. # strip leading whitespace:
  913. when defined(nimpretty): tok.literal.add "\L"
  914. if isDoc:
  915. when not defined(nimpretty): tok.literal.add "\n"
  916. inc tok.iNumber
  917. var c = toStrip
  918. while buf[pos] == ' ' and c > 0:
  919. inc pos
  920. dec c
  921. of nimlexbase.EndOfFile:
  922. tokenEndIgnore(tok, pos)
  923. lexMessagePos(L, errGenerated, pos, "end of multiline comment expected")
  924. break
  925. else:
  926. if isDoc or defined(nimpretty): tok.literal.add buf[pos]
  927. inc(pos)
  928. L.bufpos = pos
  929. when defined(nimpretty):
  930. tok.commentOffsetB = L.offsetBase + pos - 1
  931. proc scanComment(L: var TLexer, tok: var TToken) =
  932. var pos = L.bufpos
  933. var buf = L.buf
  934. tok.tokType = tkComment
  935. # iNumber contains the number of '\n' in the token
  936. tok.iNumber = 0
  937. assert buf[pos+1] == '#'
  938. when defined(nimpretty):
  939. tok.commentOffsetA = L.offsetBase + pos - 1
  940. if buf[pos+2] == '[':
  941. skipMultiLineComment(L, tok, pos+3, true)
  942. return
  943. tokenBegin(tok, pos)
  944. inc(pos, 2)
  945. var toStrip = 0
  946. while buf[pos] == ' ':
  947. inc pos
  948. inc toStrip
  949. while true:
  950. var lastBackslash = -1
  951. while buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
  952. if buf[pos] == '\\': lastBackslash = pos+1
  953. add(tok.literal, buf[pos])
  954. inc(pos)
  955. tokenEndIgnore(tok, pos)
  956. pos = handleCRLF(L, pos)
  957. buf = L.buf
  958. var indent = 0
  959. while buf[pos] == ' ':
  960. inc(pos)
  961. inc(indent)
  962. if buf[pos] == '#' and buf[pos+1] == '#':
  963. tok.literal.add "\n"
  964. inc(pos, 2)
  965. var c = toStrip
  966. while buf[pos] == ' ' and c > 0:
  967. inc pos
  968. dec c
  969. inc tok.iNumber
  970. else:
  971. if buf[pos] > ' ':
  972. L.indentAhead = indent
  973. tokenEndIgnore(tok, pos)
  974. break
  975. L.bufpos = pos
  976. when defined(nimpretty):
  977. tok.commentOffsetB = L.offsetBase + pos - 1
  978. proc skip(L: var TLexer, tok: var TToken) =
  979. var pos = L.bufpos
  980. var buf = L.buf
  981. tokenBegin(tok, pos)
  982. tok.strongSpaceA = 0
  983. when defined(nimpretty):
  984. var hasComment = false
  985. tok.commentOffsetA = L.offsetBase + pos
  986. tok.commentOffsetB = tok.commentOffsetA
  987. while true:
  988. case buf[pos]
  989. of ' ':
  990. inc(pos)
  991. inc(tok.strongSpaceA)
  992. of '\t':
  993. if not L.allowTabs: lexMessagePos(L, errGenerated, pos, "tabulators are not allowed")
  994. inc(pos)
  995. of CR, LF:
  996. tokenEndPrevious(tok, pos)
  997. when defined(nimpretty):
  998. # we are not yet in a comment, so update the comment token's line information:
  999. if not hasComment: inc tok.line
  1000. pos = handleCRLF(L, pos)
  1001. buf = L.buf
  1002. var indent = 0
  1003. while true:
  1004. if buf[pos] == ' ':
  1005. inc(pos)
  1006. inc(indent)
  1007. elif buf[pos] == '#' and buf[pos+1] == '[':
  1008. when defined(nimpretty): hasComment = true
  1009. skipMultiLineComment(L, tok, pos+2, false)
  1010. pos = L.bufpos
  1011. buf = L.buf
  1012. else:
  1013. break
  1014. tok.strongSpaceA = 0
  1015. if buf[pos] > ' ' and (buf[pos] != '#' or buf[pos+1] == '#'):
  1016. tok.indent = indent
  1017. L.currLineIndent = indent
  1018. break
  1019. of '#':
  1020. # do not skip documentation comment:
  1021. if buf[pos+1] == '#': break
  1022. when defined(nimpretty): hasComment = true
  1023. if buf[pos+1] == '[':
  1024. skipMultiLineComment(L, tok, pos+2, false)
  1025. pos = L.bufpos
  1026. buf = L.buf
  1027. else:
  1028. tokenBegin(tok, pos)
  1029. while buf[pos] notin {CR, LF, nimlexbase.EndOfFile}: inc(pos)
  1030. tokenEndIgnore(tok, pos+1)
  1031. when defined(nimpretty):
  1032. tok.commentOffsetB = L.offsetBase + pos + 1
  1033. else:
  1034. break # EndOfFile also leaves the loop
  1035. tokenEndPrevious(tok, pos-1)
  1036. L.bufpos = pos
  1037. when defined(nimpretty):
  1038. if hasComment:
  1039. tok.commentOffsetB = L.offsetBase + pos - 1
  1040. tok.tokType = tkComment
  1041. if gIndentationWidth <= 0:
  1042. gIndentationWidth = tok.indent
  1043. proc rawGetTok*(L: var TLexer, tok: var TToken) =
  1044. template atTokenEnd() {.dirty.} =
  1045. when defined(nimsuggest):
  1046. # we attach the cursor to the last *strong* token
  1047. if tok.tokType notin weakTokens:
  1048. L.previousToken.line = tok.line.uint16
  1049. L.previousToken.col = tok.col.int16
  1050. when defined(nimsuggest):
  1051. L.cursor = CursorPosition.None
  1052. fillToken(tok)
  1053. if L.indentAhead >= 0:
  1054. tok.indent = L.indentAhead
  1055. L.currLineIndent = L.indentAhead
  1056. L.indentAhead = -1
  1057. else:
  1058. tok.indent = -1
  1059. skip(L, tok)
  1060. when defined(nimpretty):
  1061. if tok.tokType == tkComment:
  1062. L.indentAhead = L.currLineIndent
  1063. return
  1064. var c = L.buf[L.bufpos]
  1065. tok.line = L.lineNumber
  1066. tok.col = getColNumber(L, L.bufpos)
  1067. if c in SymStartChars - {'r', 'R'}:
  1068. getSymbol(L, tok)
  1069. else:
  1070. case c
  1071. of '#':
  1072. scanComment(L, tok)
  1073. of '*':
  1074. # '*:' is unfortunately a special case, because it is two tokens in
  1075. # 'var v*: int'.
  1076. if L.buf[L.bufpos+1] == ':' and L.buf[L.bufpos+2] notin OpChars:
  1077. var h = 0 !& ord('*')
  1078. endOperator(L, tok, L.bufpos+1, h)
  1079. else:
  1080. getOperator(L, tok)
  1081. of ',':
  1082. tok.tokType = tkComma
  1083. inc(L.bufpos)
  1084. of 'r', 'R':
  1085. if L.buf[L.bufpos + 1] == '\"':
  1086. inc(L.bufpos)
  1087. getString(L, tok, true)
  1088. else:
  1089. getSymbol(L, tok)
  1090. of '(':
  1091. inc(L.bufpos)
  1092. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1093. tok.tokType = tkParDotLe
  1094. inc(L.bufpos)
  1095. else:
  1096. tok.tokType = tkParLe
  1097. when defined(nimsuggest):
  1098. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col < L.config.m.trackPos.col and
  1099. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideCon:
  1100. L.config.m.trackPos.col = tok.col.int16
  1101. of ')':
  1102. tok.tokType = tkParRi
  1103. inc(L.bufpos)
  1104. of '[':
  1105. inc(L.bufpos)
  1106. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1107. tok.tokType = tkBracketDotLe
  1108. inc(L.bufpos)
  1109. elif L.buf[L.bufpos] == ':':
  1110. tok.tokType = tkBracketLeColon
  1111. inc(L.bufpos)
  1112. else:
  1113. tok.tokType = tkBracketLe
  1114. of ']':
  1115. tok.tokType = tkBracketRi
  1116. inc(L.bufpos)
  1117. of '.':
  1118. when defined(nimsuggest):
  1119. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col+1 == L.config.m.trackPos.col and
  1120. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideSug:
  1121. tok.tokType = tkDot
  1122. L.cursor = CursorPosition.InToken
  1123. L.config.m.trackPos.col = tok.col.int16
  1124. inc(L.bufpos)
  1125. atTokenEnd()
  1126. return
  1127. if L.buf[L.bufpos+1] == ']':
  1128. tok.tokType = tkBracketDotRi
  1129. inc(L.bufpos, 2)
  1130. elif L.buf[L.bufpos+1] == '}':
  1131. tok.tokType = tkCurlyDotRi
  1132. inc(L.bufpos, 2)
  1133. elif L.buf[L.bufpos+1] == ')':
  1134. tok.tokType = tkParDotRi
  1135. inc(L.bufpos, 2)
  1136. else:
  1137. getOperator(L, tok)
  1138. of '{':
  1139. inc(L.bufpos)
  1140. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1141. tok.tokType = tkCurlyDotLe
  1142. inc(L.bufpos)
  1143. else:
  1144. tok.tokType = tkCurlyLe
  1145. of '}':
  1146. tok.tokType = tkCurlyRi
  1147. inc(L.bufpos)
  1148. of ';':
  1149. tok.tokType = tkSemiColon
  1150. inc(L.bufpos)
  1151. of '`':
  1152. tok.tokType = tkAccent
  1153. inc(L.bufpos)
  1154. of '_':
  1155. inc(L.bufpos)
  1156. if L.buf[L.bufpos] notin SymChars+{'_'}:
  1157. tok.tokType = tkSymbol
  1158. tok.ident = L.cache.getIdent("_")
  1159. else:
  1160. tok.literal = $c
  1161. tok.tokType = tkInvalid
  1162. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1163. of '\"':
  1164. # check for generalized raw string literal:
  1165. var rawMode = L.bufpos > 0 and L.buf[L.bufpos-1] in SymChars
  1166. getString(L, tok, rawMode)
  1167. if rawMode:
  1168. # tkRStrLit -> tkGStrLit
  1169. # tkTripleStrLit -> tkGTripleStrLit
  1170. inc(tok.tokType, 2)
  1171. of '\'':
  1172. tok.tokType = tkCharLit
  1173. getCharacter(L, tok)
  1174. tok.tokType = tkCharLit
  1175. of '0'..'9':
  1176. getNumber(L, tok)
  1177. let c = L.buf[L.bufpos]
  1178. if c in SymChars+{'_'}:
  1179. lexMessage(L, errGenerated, "invalid token: no whitespace between number and identifier")
  1180. else:
  1181. if c in OpChars:
  1182. getOperator(L, tok)
  1183. elif c == nimlexbase.EndOfFile:
  1184. tok.tokType = tkEof
  1185. tok.indent = 0
  1186. else:
  1187. tok.literal = $c
  1188. tok.tokType = tkInvalid
  1189. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1190. inc(L.bufpos)
  1191. atTokenEnd()
  1192. proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream;
  1193. cache: IdentCache; config: ConfigRef): int =
  1194. var lex: TLexer
  1195. var tok: TToken
  1196. initToken(tok)
  1197. openLexer(lex, fileIdx, inputstream, cache, config)
  1198. while true:
  1199. rawGetTok(lex, tok)
  1200. result = tok.indent
  1201. if result > 0 or tok.tokType == tkEof: break
  1202. closeLexer(lex)
  1203. proc getPrecedence*(ident: PIdent): int =
  1204. ## assumes ident is binary operator already
  1205. var tok: TToken
  1206. initToken(tok)
  1207. tok.ident = ident
  1208. tok.tokType =
  1209. if tok.ident.id in ord(tokKeywordLow) - ord(tkSymbol) .. ord(tokKeywordHigh) - ord(tkSymbol):
  1210. TTokType(tok.ident.id + ord(tkSymbol))
  1211. else: tkOpr
  1212. getPrecedence(tok, false)