lexer.nim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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, parseutils
  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 indentation 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. proc getLineInfo*(L: TLexer, tok: TToken): TLineInfo {.inline.} =
  138. result = newLineInfo(L.fileIdx, tok.line, tok.col)
  139. when defined(nimpretty):
  140. result.offsetA = tok.offsetA
  141. result.offsetB = tok.offsetB
  142. result.commentOffsetA = tok.commentOffsetA
  143. result.commentOffsetB = tok.commentOffsetB
  144. proc isKeyword*(kind: TTokType): bool =
  145. result = (kind >= tokKeywordLow) and (kind <= tokKeywordHigh)
  146. template ones(n): untyped = ((1 shl n)-1) # for utf-8 conversion
  147. proc isNimIdentifier*(s: string): bool =
  148. let sLen = s.len
  149. if sLen > 0 and s[0] in SymStartChars:
  150. var i = 1
  151. while i < sLen:
  152. if s[i] == '_': inc(i)
  153. if i < sLen and s[i] notin SymChars: return
  154. inc(i)
  155. result = true
  156. proc `$`*(tok: TToken): string =
  157. case tok.tokType
  158. of tkIntLit..tkInt64Lit: result = $tok.iNumber
  159. of tkFloatLit..tkFloat64Lit: result = $tok.fNumber
  160. of tkInvalid, tkStrLit..tkCharLit, tkComment: result = tok.literal
  161. of tkParLe..tkColon, tkEof, tkAccent:
  162. result = TokTypeToStr[tok.tokType]
  163. else:
  164. if tok.ident != nil:
  165. result = tok.ident.s
  166. else:
  167. result = ""
  168. proc prettyTok*(tok: TToken): string =
  169. if isKeyword(tok.tokType): result = "keyword " & tok.ident.s
  170. else: result = $tok
  171. proc printTok*(conf: ConfigRef; tok: TToken) =
  172. msgWriteln(conf, $tok.line & ":" & $tok.col & "\t" &
  173. TokTypeToStr[tok.tokType] & " " & $tok)
  174. proc initToken*(L: var TToken) =
  175. L.tokType = tkInvalid
  176. L.iNumber = 0
  177. L.indent = 0
  178. L.strongSpaceA = 0
  179. L.literal = ""
  180. L.fNumber = 0.0
  181. L.base = base10
  182. L.ident = nil
  183. when defined(nimpretty):
  184. L.commentOffsetA = 0
  185. L.commentOffsetB = 0
  186. proc fillToken(L: var TToken) =
  187. L.tokType = tkInvalid
  188. L.iNumber = 0
  189. L.indent = 0
  190. L.strongSpaceA = 0
  191. setLen(L.literal, 0)
  192. L.fNumber = 0.0
  193. L.base = base10
  194. L.ident = nil
  195. when defined(nimpretty):
  196. L.commentOffsetA = 0
  197. L.commentOffsetB = 0
  198. proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
  199. cache: IdentCache; config: ConfigRef) =
  200. openBaseLexer(lex, inputstream)
  201. lex.fileIdx = fileIdx
  202. lex.indentAhead = -1
  203. lex.currLineIndent = 0
  204. inc(lex.lineNumber, inputstream.lineOffset)
  205. lex.cache = cache
  206. when defined(nimsuggest):
  207. lex.previousToken.fileIndex = fileIdx
  208. lex.config = config
  209. proc openLexer*(lex: var TLexer, filename: AbsoluteFile, inputstream: PLLStream;
  210. cache: IdentCache; config: ConfigRef) =
  211. openLexer(lex, fileInfoIdx(config, filename), inputstream, cache, config)
  212. proc closeLexer*(lex: var TLexer) =
  213. if lex.config != nil:
  214. inc(lex.config.linesCompiled, lex.lineNumber)
  215. closeBaseLexer(lex)
  216. proc getLineInfo(L: TLexer): TLineInfo =
  217. result = newLineInfo(L.fileIdx, L.lineNumber, getColNumber(L, L.bufpos))
  218. proc dispMessage(L: TLexer; info: TLineInfo; msg: TMsgKind; arg: string) =
  219. if L.errorHandler.isNil:
  220. msgs.message(L.config, info, msg, arg)
  221. else:
  222. L.errorHandler(L.config, info, msg, arg)
  223. proc lexMessage*(L: TLexer, msg: TMsgKind, arg = "") =
  224. L.dispMessage(getLineInfo(L), msg, arg)
  225. proc lexMessageTok*(L: TLexer, msg: TMsgKind, tok: TToken, arg = "") =
  226. var info = newLineInfo(L.fileIdx, tok.line, tok.col)
  227. L.dispMessage(info, msg, arg)
  228. proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") =
  229. var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart)
  230. L.dispMessage(info, msg, arg)
  231. proc matchTwoChars(L: TLexer, first: char, second: set[char]): bool =
  232. result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second)
  233. template tokenBegin(tok, pos) {.dirty.} =
  234. when defined(nimsuggest):
  235. var colA = getColNumber(L, pos)
  236. when defined(nimpretty):
  237. tok.offsetA = L.offsetBase + pos
  238. template tokenEnd(tok, pos) {.dirty.} =
  239. when defined(nimsuggest):
  240. let colB = getColNumber(L, pos)+1
  241. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  242. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  243. L.cursor = CursorPosition.InToken
  244. L.config.m.trackPos.col = colA.int16
  245. colA = 0
  246. when defined(nimpretty):
  247. tok.offsetB = L.offsetBase + pos
  248. template tokenEndIgnore(tok, pos) =
  249. when defined(nimsuggest):
  250. let colB = getColNumber(L, pos)
  251. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  252. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  253. L.config.m.trackPos.fileIndex = trackPosInvalidFileIdx
  254. L.config.m.trackPos.line = 0'u16
  255. colA = 0
  256. when defined(nimpretty):
  257. tok.offsetB = L.offsetBase + pos
  258. template tokenEndPrevious(tok, pos) =
  259. when defined(nimsuggest):
  260. # when we detect the cursor in whitespace, we attach the track position
  261. # to the token that came before that, but only if we haven't detected
  262. # the cursor in a string literal or comment:
  263. let colB = getColNumber(L, pos)
  264. if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
  265. L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
  266. L.cursor = CursorPosition.BeforeToken
  267. L.config.m.trackPos = L.previousToken
  268. L.config.m.trackPosAttached = true
  269. colA = 0
  270. when defined(nimpretty):
  271. tok.offsetB = L.offsetBase + pos
  272. template eatChar(L: var TLexer, t: var TToken, replacementChar: char) =
  273. add(t.literal, replacementChar)
  274. inc(L.bufpos)
  275. template eatChar(L: var TLexer, t: var TToken) =
  276. add(t.literal, L.buf[L.bufpos])
  277. inc(L.bufpos)
  278. proc getNumber(L: var TLexer, result: var TToken) =
  279. proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]): Natural =
  280. var pos = L.bufpos # use registers for pos, buf
  281. result = 0
  282. while true:
  283. if L.buf[pos] in chars:
  284. add(tok.literal, L.buf[pos])
  285. inc(pos)
  286. inc(result)
  287. else:
  288. break
  289. if L.buf[pos] == '_':
  290. if L.buf[pos+1] notin chars:
  291. lexMessage(L, errGenerated,
  292. "only single underscores may occur in a token and token may not " &
  293. "end with an underscore: e.g. '1__1' and '1_' are invalid")
  294. break
  295. add(tok.literal, '_')
  296. inc(pos)
  297. L.bufpos = pos
  298. proc matchChars(L: var TLexer, tok: var TToken, chars: set[char]) =
  299. var pos = L.bufpos # use registers for pos, buf
  300. while L.buf[pos] in chars:
  301. add(tok.literal, L.buf[pos])
  302. inc(pos)
  303. L.bufpos = pos
  304. proc lexMessageLitNum(L: var TLexer, msg: string, startpos: int, msgKind = errGenerated) =
  305. # Used to get slightly human friendlier err messages.
  306. const literalishChars = {'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', 'O',
  307. 'c', 'C', 'b', 'B', '_', '.', '\'', 'd', 'i', 'u'}
  308. var msgPos = L.bufpos
  309. var t: TToken
  310. t.literal = ""
  311. L.bufpos = startpos # Use L.bufpos as pos because of matchChars
  312. matchChars(L, t, literalishChars)
  313. # We must verify +/- specifically so that we're not past the literal
  314. if L.buf[L.bufpos] in {'+', '-'} and
  315. L.buf[L.bufpos - 1] in {'e', 'E'}:
  316. add(t.literal, L.buf[L.bufpos])
  317. inc(L.bufpos)
  318. matchChars(L, t, literalishChars)
  319. if L.buf[L.bufpos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}:
  320. inc(L.bufpos)
  321. add(t.literal, L.buf[L.bufpos])
  322. matchChars(L, t, {'0'..'9'})
  323. L.bufpos = msgPos
  324. lexMessage(L, msgKind, msg % t.literal)
  325. var
  326. startpos, endpos: int
  327. xi: BiggestInt
  328. isBase10 = true
  329. numDigits = 0
  330. const
  331. # 'c', 'C' is deprecated
  332. baseCodeChars = {'X', 'x', 'o', 'b', 'B', 'c', 'C'}
  333. literalishChars = baseCodeChars + {'A'..'F', 'a'..'f', '0'..'9', '_', '\''}
  334. floatTypes = {tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit}
  335. result.tokType = tkIntLit # int literal until we know better
  336. result.literal = ""
  337. result.base = base10
  338. startpos = L.bufpos
  339. tokenBegin(result, startpos)
  340. # First stage: find out base, make verifications, build token literal string
  341. # {'c', 'C'} is added for deprecation reasons to provide a clear error message
  342. if L.buf[L.bufpos] == '0' and L.buf[L.bufpos + 1] in baseCodeChars + {'c', 'C', 'O'}:
  343. isBase10 = false
  344. eatChar(L, result, '0')
  345. case L.buf[L.bufpos]
  346. of 'c', 'C':
  347. lexMessageLitNum(L,
  348. "$1 will soon be invalid for oct literals; Use '0o' " &
  349. "for octals. 'c', 'C' prefix",
  350. startpos,
  351. warnDeprecated)
  352. eatChar(L, result, 'c')
  353. numDigits = matchUnderscoreChars(L, result, {'0'..'7'})
  354. of 'O':
  355. lexMessageLitNum(L, "$1 is an invalid int literal; For octal literals " &
  356. "use the '0o' prefix.", startpos)
  357. of 'x', 'X':
  358. eatChar(L, result, 'x')
  359. numDigits = matchUnderscoreChars(L, result, {'0'..'9', 'a'..'f', 'A'..'F'})
  360. of 'o':
  361. eatChar(L, result, 'o')
  362. numDigits = matchUnderscoreChars(L, result, {'0'..'7'})
  363. of 'b', 'B':
  364. eatChar(L, result, 'b')
  365. numDigits = matchUnderscoreChars(L, result, {'0'..'1'})
  366. else:
  367. internalError(L.config, getLineInfo(L), "getNumber")
  368. if numDigits == 0:
  369. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  370. else:
  371. discard matchUnderscoreChars(L, result, {'0'..'9'})
  372. if (L.buf[L.bufpos] == '.') and (L.buf[L.bufpos + 1] in {'0'..'9'}):
  373. result.tokType = tkFloatLit
  374. eatChar(L, result, '.')
  375. discard matchUnderscoreChars(L, result, {'0'..'9'})
  376. if L.buf[L.bufpos] in {'e', 'E'}:
  377. result.tokType = tkFloatLit
  378. eatChar(L, result, 'e')
  379. if L.buf[L.bufpos] in {'+', '-'}:
  380. eatChar(L, result)
  381. discard matchUnderscoreChars(L, result, {'0'..'9'})
  382. endpos = L.bufpos
  383. # Second stage, find out if there's a datatype suffix and handle it
  384. var postPos = endpos
  385. if L.buf[postPos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}:
  386. if L.buf[postPos] == '\'':
  387. inc(postPos)
  388. case L.buf[postPos]
  389. of 'f', 'F':
  390. inc(postPos)
  391. if (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  392. result.tokType = tkFloat32Lit
  393. inc(postPos, 2)
  394. elif (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  395. result.tokType = tkFloat64Lit
  396. inc(postPos, 2)
  397. elif (L.buf[postPos] == '1') and
  398. (L.buf[postPos + 1] == '2') and
  399. (L.buf[postPos + 2] == '8'):
  400. result.tokType = tkFloat128Lit
  401. inc(postPos, 3)
  402. else: # "f" alone defaults to float32
  403. result.tokType = tkFloat32Lit
  404. of 'd', 'D': # ad hoc convenience shortcut for f64
  405. inc(postPos)
  406. result.tokType = tkFloat64Lit
  407. of 'i', 'I':
  408. inc(postPos)
  409. if (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  410. result.tokType = tkInt64Lit
  411. inc(postPos, 2)
  412. elif (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  413. result.tokType = tkInt32Lit
  414. inc(postPos, 2)
  415. elif (L.buf[postPos] == '1') and (L.buf[postPos + 1] == '6'):
  416. result.tokType = tkInt16Lit
  417. inc(postPos, 2)
  418. elif (L.buf[postPos] == '8'):
  419. result.tokType = tkInt8Lit
  420. inc(postPos)
  421. else:
  422. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  423. of 'u', 'U':
  424. inc(postPos)
  425. if (L.buf[postPos] == '6') and (L.buf[postPos + 1] == '4'):
  426. result.tokType = tkUInt64Lit
  427. inc(postPos, 2)
  428. elif (L.buf[postPos] == '3') and (L.buf[postPos + 1] == '2'):
  429. result.tokType = tkUInt32Lit
  430. inc(postPos, 2)
  431. elif (L.buf[postPos] == '1') and (L.buf[postPos + 1] == '6'):
  432. result.tokType = tkUInt16Lit
  433. inc(postPos, 2)
  434. elif (L.buf[postPos] == '8'):
  435. result.tokType = tkUInt8Lit
  436. inc(postPos)
  437. else:
  438. result.tokType = tkUIntLit
  439. else:
  440. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  441. # Is there still a literalish char awaiting? Then it's an error!
  442. if L.buf[postPos] in literalishChars or
  443. (L.buf[postPos] == '.' and L.buf[postPos + 1] in {'0'..'9'}):
  444. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  445. # Third stage, extract actual number
  446. L.bufpos = startpos # restore position
  447. var pos: int = startpos
  448. try:
  449. if (L.buf[pos] == '0') and (L.buf[pos + 1] in baseCodeChars):
  450. inc(pos, 2)
  451. xi = 0 # it is a base prefix
  452. case L.buf[pos - 1]
  453. of 'b', 'B':
  454. result.base = base2
  455. while pos < endpos:
  456. if L.buf[pos] != '_':
  457. xi = `shl`(xi, 1) or (ord(L.buf[pos]) - ord('0'))
  458. inc(pos)
  459. # 'c', 'C' is deprecated
  460. of 'o', 'c', 'C':
  461. result.base = base8
  462. while pos < endpos:
  463. if L.buf[pos] != '_':
  464. xi = `shl`(xi, 3) or (ord(L.buf[pos]) - ord('0'))
  465. inc(pos)
  466. of 'x', 'X':
  467. result.base = base16
  468. while pos < endpos:
  469. case L.buf[pos]
  470. of '_':
  471. inc(pos)
  472. of '0'..'9':
  473. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('0'))
  474. inc(pos)
  475. of 'a'..'f':
  476. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('a') + 10)
  477. inc(pos)
  478. of 'A'..'F':
  479. xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('A') + 10)
  480. inc(pos)
  481. else:
  482. break
  483. else:
  484. internalError(L.config, getLineInfo(L), "getNumber")
  485. case result.tokType
  486. of tkIntLit, tkInt64Lit: result.iNumber = xi
  487. of tkInt8Lit: result.iNumber = ashr(xi shl 56, 56)
  488. of tkInt16Lit: result.iNumber = ashr(xi shl 48, 48)
  489. of tkInt32Lit: result.iNumber = ashr(xi shl 32, 32)
  490. of tkUIntLit, tkUInt64Lit: result.iNumber = xi
  491. of tkUInt8Lit: result.iNumber = xi and 0xff
  492. of tkUInt16Lit: result.iNumber = xi and 0xffff
  493. of tkUInt32Lit: result.iNumber = xi and 0xffffffff
  494. of tkFloat32Lit:
  495. result.fNumber = (cast[PFloat32](addr(xi)))[]
  496. # note: this code is endian neutral!
  497. # XXX: Test this on big endian machine!
  498. of tkFloat64Lit, tkFloatLit:
  499. result.fNumber = (cast[PFloat64](addr(xi)))[]
  500. else: internalError(L.config, getLineInfo(L), "getNumber")
  501. # Bounds checks. Non decimal literals are allowed to overflow the range of
  502. # the datatype as long as their pattern don't overflow _bitwise_, hence
  503. # below checks of signed sizes against uint*.high is deliberate:
  504. # (0x80'u8 = 128, 0x80'i8 = -128, etc == OK)
  505. if result.tokType notin floatTypes:
  506. let outOfRange = case result.tokType:
  507. of tkUInt8Lit, tkUInt16Lit, tkUInt32Lit: result.iNumber != xi
  508. of tkInt8Lit: (xi > BiggestInt(uint8.high))
  509. of tkInt16Lit: (xi > BiggestInt(uint16.high))
  510. of tkInt32Lit: (xi > BiggestInt(uint32.high))
  511. else: false
  512. if outOfRange:
  513. #echo "out of range num: ", result.iNumber, " vs ", xi
  514. lexMessageLitNum(L, "number out of range: '$1'", startpos)
  515. else:
  516. case result.tokType
  517. of floatTypes:
  518. result.fNumber = parseFloat(result.literal)
  519. of tkUInt64Lit, tkUIntLit:
  520. var iNumber: uint64
  521. var len: int
  522. try:
  523. len = parseBiggestUInt(result.literal, iNumber)
  524. except ValueError:
  525. raise newException(OverflowError, "number out of range: " & $result.literal)
  526. if len != result.literal.len:
  527. raise newException(ValueError, "invalid integer: " & $result.literal)
  528. result.iNumber = cast[int64](iNumber)
  529. else:
  530. var iNumber: int64
  531. var len: int
  532. try:
  533. len = parseBiggestInt(result.literal, iNumber)
  534. except ValueError:
  535. raise newException(OverflowError, "number out of range: " & $result.literal)
  536. if len != result.literal.len:
  537. raise newException(ValueError, "invalid integer: " & $result.literal)
  538. result.iNumber = iNumber
  539. # Explicit bounds checks. Only T.high needs to be considered
  540. # since result.iNumber can't be negative.
  541. let outOfRange =
  542. case result.tokType
  543. of tkInt8Lit: result.iNumber > int8.high
  544. of tkUInt8Lit: result.iNumber > BiggestInt(uint8.high)
  545. of tkInt16Lit: result.iNumber > int16.high
  546. of tkUInt16Lit: result.iNumber > BiggestInt(uint16.high)
  547. of tkInt32Lit: result.iNumber > int32.high
  548. of tkUInt32Lit: result.iNumber > BiggestInt(uint32.high)
  549. else: false
  550. if outOfRange: lexMessageLitNum(L, "number out of range: '$1'", startpos)
  551. # Promote int literal to int64? Not always necessary, but more consistent
  552. if result.tokType == tkIntLit:
  553. if result.iNumber > high(int32):
  554. result.tokType = tkInt64Lit
  555. except ValueError:
  556. lexMessageLitNum(L, "invalid number: '$1'", startpos)
  557. except OverflowError, RangeError:
  558. lexMessageLitNum(L, "number out of range: '$1'", startpos)
  559. tokenEnd(result, postPos-1)
  560. L.bufpos = postPos
  561. proc handleHexChar(L: var TLexer, xi: var int; position: range[0..4]) =
  562. template invalid() =
  563. lexMessage(L, errGenerated,
  564. "expected a hex digit, but found: " & L.buf[L.bufpos] &
  565. "; maybe prepend with 0")
  566. case L.buf[L.bufpos]
  567. of '0'..'9':
  568. xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('0'))
  569. inc(L.bufpos)
  570. of 'a'..'f':
  571. xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('a') + 10)
  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 '"', '\'':
  577. if position <= 1: invalid()
  578. # do not progress the bufpos here.
  579. if position == 0: inc(L.bufpos)
  580. else:
  581. invalid()
  582. # Need to progress for `nim check`
  583. inc(L.bufpos)
  584. proc handleDecChars(L: var TLexer, xi: var int) =
  585. while L.buf[L.bufpos] in {'0'..'9'}:
  586. xi = (xi * 10) + (ord(L.buf[L.bufpos]) - ord('0'))
  587. inc(L.bufpos)
  588. proc addUnicodeCodePoint(s: var string, i: int) =
  589. let i = cast[uint](i)
  590. # inlined toUTF-8 to avoid unicode and strutils dependencies.
  591. let pos = s.len
  592. if i <= 127:
  593. s.setLen(pos+1)
  594. s[pos+0] = chr(i)
  595. elif i <= 0x07FF:
  596. s.setLen(pos+2)
  597. s[pos+0] = chr((i shr 6) or 0b110_00000)
  598. s[pos+1] = chr((i and ones(6)) or 0b10_0000_00)
  599. elif i <= 0xFFFF:
  600. s.setLen(pos+3)
  601. s[pos+0] = chr(i shr 12 or 0b1110_0000)
  602. s[pos+1] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  603. s[pos+2] = chr(i and ones(6) or 0b10_0000_00)
  604. elif i <= 0x001FFFFF:
  605. s.setLen(pos+4)
  606. s[pos+0] = chr(i shr 18 or 0b1111_0000)
  607. s[pos+1] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  608. s[pos+2] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  609. s[pos+3] = chr(i and ones(6) or 0b10_0000_00)
  610. elif i <= 0x03FFFFFF:
  611. s.setLen(pos+5)
  612. s[pos+0] = chr(i shr 24 or 0b111110_00)
  613. s[pos+1] = chr(i shr 18 and ones(6) or 0b10_0000_00)
  614. s[pos+2] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  615. s[pos+3] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  616. s[pos+4] = chr(i and ones(6) or 0b10_0000_00)
  617. elif i <= 0x7FFFFFFF:
  618. s.setLen(pos+6)
  619. s[pos+0] = chr(i shr 30 or 0b1111110_0)
  620. s[pos+1] = chr(i shr 24 and ones(6) or 0b10_0000_00)
  621. s[pos+2] = chr(i shr 18 and ones(6) or 0b10_0000_00)
  622. s[pos+3] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  623. s[pos+4] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  624. s[pos+5] = chr(i and ones(6) or 0b10_0000_00)
  625. proc getEscapedChar(L: var TLexer, tok: var TToken) =
  626. inc(L.bufpos) # skip '\'
  627. case L.buf[L.bufpos]
  628. of 'n', 'N':
  629. if L.config.oldNewlines:
  630. if tok.tokType == tkCharLit:
  631. lexMessage(L, errGenerated, "\\n not allowed in character literal")
  632. add(tok.literal, L.config.target.tnl)
  633. else:
  634. add(tok.literal, '\L')
  635. inc(L.bufpos)
  636. of 'p', 'P':
  637. if tok.tokType == tkCharLit:
  638. lexMessage(L, errGenerated, "\\p not allowed in character literal")
  639. add(tok.literal, L.config.target.tnl)
  640. inc(L.bufpos)
  641. of 'r', 'R', 'c', 'C':
  642. add(tok.literal, CR)
  643. inc(L.bufpos)
  644. of 'l', 'L':
  645. add(tok.literal, LF)
  646. inc(L.bufpos)
  647. of 'f', 'F':
  648. add(tok.literal, FF)
  649. inc(L.bufpos)
  650. of 'e', 'E':
  651. add(tok.literal, ESC)
  652. inc(L.bufpos)
  653. of 'a', 'A':
  654. add(tok.literal, BEL)
  655. inc(L.bufpos)
  656. of 'b', 'B':
  657. add(tok.literal, BACKSPACE)
  658. inc(L.bufpos)
  659. of 'v', 'V':
  660. add(tok.literal, VT)
  661. inc(L.bufpos)
  662. of 't', 'T':
  663. add(tok.literal, '\t')
  664. inc(L.bufpos)
  665. of '\'', '\"':
  666. add(tok.literal, L.buf[L.bufpos])
  667. inc(L.bufpos)
  668. of '\\':
  669. add(tok.literal, '\\')
  670. inc(L.bufpos)
  671. of 'x', 'X':
  672. inc(L.bufpos)
  673. var xi = 0
  674. handleHexChar(L, xi, 1)
  675. handleHexChar(L, xi, 2)
  676. add(tok.literal, chr(xi))
  677. of 'u', 'U':
  678. if tok.tokType == tkCharLit:
  679. lexMessage(L, errGenerated, "\\u not allowed in character literal")
  680. inc(L.bufpos)
  681. var xi = 0
  682. if L.buf[L.bufpos] == '{':
  683. inc(L.bufpos)
  684. var start = L.bufpos
  685. while L.buf[L.bufpos] != '}':
  686. handleHexChar(L, xi, 0)
  687. if start == L.bufpos:
  688. lexMessage(L, errGenerated,
  689. "Unicode codepoint cannot be empty")
  690. inc(L.bufpos)
  691. if xi > 0x10FFFF:
  692. let hex = ($L.buf)[start..L.bufpos-2]
  693. lexMessage(L, errGenerated,
  694. "Unicode codepoint must be lower than 0x10FFFF, but was: " & hex)
  695. else:
  696. handleHexChar(L, xi, 1)
  697. handleHexChar(L, xi, 2)
  698. handleHexChar(L, xi, 3)
  699. handleHexChar(L, xi, 4)
  700. addUnicodeCodePoint(tok.literal, xi)
  701. of '0'..'9':
  702. if matchTwoChars(L, '0', {'0'..'9'}):
  703. lexMessage(L, warnOctalEscape)
  704. var xi = 0
  705. handleDecChars(L, xi)
  706. if (xi <= 255): add(tok.literal, chr(xi))
  707. else: lexMessage(L, errGenerated, "invalid character constant")
  708. else: lexMessage(L, errGenerated, "invalid character constant")
  709. proc newString(s: cstring, len: int): string =
  710. ## XXX, how come there is no support for this?
  711. result = newString(len)
  712. for i in 0 ..< len:
  713. result[i] = s[i]
  714. proc handleCRLF(L: var TLexer, pos: int): int =
  715. template registerLine =
  716. let col = L.getColNumber(pos)
  717. if col > MaxLineLength:
  718. lexMessagePos(L, hintLineTooLong, pos)
  719. case L.buf[pos]
  720. of CR:
  721. registerLine()
  722. result = nimlexbase.handleCR(L, pos)
  723. of LF:
  724. registerLine()
  725. result = nimlexbase.handleLF(L, pos)
  726. else: result = pos
  727. type
  728. StringMode = enum
  729. normal,
  730. raw,
  731. generalized
  732. proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
  733. var pos = L.bufpos
  734. var line = L.lineNumber # save linenumber for better error message
  735. tokenBegin(tok, pos - ord(mode == raw))
  736. inc pos # skip "
  737. if L.buf[pos] == '\"' and L.buf[pos+1] == '\"':
  738. tok.tokType = tkTripleStrLit # long string literal:
  739. inc(pos, 2) # skip ""
  740. # skip leading newline:
  741. if L.buf[pos] in {' ', '\t'}:
  742. var newpos = pos+1
  743. while L.buf[newpos] in {' ', '\t'}: inc newpos
  744. if L.buf[newpos] in {CR, LF}: pos = newpos
  745. pos = handleCRLF(L, pos)
  746. while true:
  747. case L.buf[pos]
  748. of '\"':
  749. if L.buf[pos+1] == '\"' and L.buf[pos+2] == '\"' and
  750. L.buf[pos+3] != '\"':
  751. tokenEndIgnore(tok, pos+2)
  752. L.bufpos = pos + 3 # skip the three """
  753. break
  754. add(tok.literal, '\"')
  755. inc(pos)
  756. of CR, LF:
  757. tokenEndIgnore(tok, pos)
  758. pos = handleCRLF(L, pos)
  759. add(tok.literal, "\n")
  760. of nimlexbase.EndOfFile:
  761. tokenEndIgnore(tok, pos)
  762. var line2 = L.lineNumber
  763. L.lineNumber = line
  764. lexMessagePos(L, errGenerated, L.lineStart, "closing \"\"\" expected, but end of file reached")
  765. L.lineNumber = line2
  766. L.bufpos = pos
  767. break
  768. else:
  769. add(tok.literal, L.buf[pos])
  770. inc(pos)
  771. else:
  772. # ordinary string literal
  773. if mode != normal: tok.tokType = tkRStrLit
  774. else: tok.tokType = tkStrLit
  775. while true:
  776. var c = L.buf[pos]
  777. if c == '\"':
  778. if mode != normal and L.buf[pos+1] == '\"':
  779. inc(pos, 2)
  780. add(tok.literal, '"')
  781. else:
  782. tokenEndIgnore(tok, pos)
  783. inc(pos) # skip '"'
  784. break
  785. elif c in {CR, LF, nimlexbase.EndOfFile}:
  786. tokenEndIgnore(tok, pos)
  787. lexMessage(L, errGenerated, "closing \" expected")
  788. break
  789. elif (c == '\\') and mode == normal:
  790. L.bufpos = pos
  791. getEscapedChar(L, tok)
  792. pos = L.bufpos
  793. else:
  794. add(tok.literal, c)
  795. inc(pos)
  796. L.bufpos = pos
  797. proc getCharacter(L: var TLexer, tok: var TToken) =
  798. tokenBegin(tok, L.bufpos)
  799. inc(L.bufpos) # skip '
  800. var c = L.buf[L.bufpos]
  801. case c
  802. of '\0'..pred(' '), '\'':
  803. lexMessage(L, errGenerated, "invalid character literal")
  804. tok.literal = $c
  805. of '\\': getEscapedChar(L, tok)
  806. else:
  807. tok.literal = $c
  808. inc(L.bufpos)
  809. if L.buf[L.bufpos] != '\'':
  810. lexMessage(L, errGenerated, "missing closing ' for character literal")
  811. tokenEndIgnore(tok, L.bufpos)
  812. inc(L.bufpos) # skip '
  813. proc getSymbol(L: var TLexer, tok: var TToken) =
  814. var h: Hash = 0
  815. var pos = L.bufpos
  816. tokenBegin(tok, pos)
  817. var suspicious = false
  818. while true:
  819. var c = L.buf[pos]
  820. case c
  821. of 'a'..'z', '0'..'9', '\x80'..'\xFF':
  822. h = h !& ord(c)
  823. inc(pos)
  824. of 'A'..'Z':
  825. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  826. h = h !& ord(c)
  827. inc(pos)
  828. suspicious = true
  829. of '_':
  830. if L.buf[pos+1] notin SymChars:
  831. lexMessage(L, errGenerated, "invalid token: trailing underscore")
  832. break
  833. inc(pos)
  834. suspicious = true
  835. else: break
  836. tokenEnd(tok, pos-1)
  837. h = !$h
  838. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  839. if (tok.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
  840. (tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
  841. tok.tokType = tkSymbol
  842. else:
  843. tok.tokType = TTokType(tok.ident.id + ord(tkSymbol))
  844. if suspicious and {optStyleHint, optStyleError} * L.config.globalOptions != {}:
  845. lintReport(L.config, getLineInfo(L), tok.ident.s.normalize, tok.ident.s)
  846. L.bufpos = pos
  847. proc endOperator(L: var TLexer, tok: var TToken, pos: int,
  848. hash: Hash) {.inline.} =
  849. var h = !$hash
  850. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  851. if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr
  852. else: tok.tokType = TTokType(tok.ident.id - oprLow + ord(tkColon))
  853. L.bufpos = pos
  854. proc getOperator(L: var TLexer, tok: var TToken) =
  855. var pos = L.bufpos
  856. tokenBegin(tok, pos)
  857. var h: Hash = 0
  858. while true:
  859. var c = L.buf[pos]
  860. if c notin OpChars: break
  861. h = h !& ord(c)
  862. inc(pos)
  863. endOperator(L, tok, pos, h)
  864. tokenEnd(tok, pos-1)
  865. # advance pos but don't store it in L.bufpos so the next token (which might
  866. # be an operator too) gets the preceding spaces:
  867. tok.strongSpaceB = 0
  868. while L.buf[pos] == ' ':
  869. inc pos
  870. inc tok.strongSpaceB
  871. if L.buf[pos] in {CR, LF, nimlexbase.EndOfFile}:
  872. tok.strongSpaceB = -1
  873. proc getPrecedence*(tok: TToken, strongSpaces: bool): int =
  874. ## Calculates the precedence of the given token.
  875. template considerStrongSpaces(x): untyped =
  876. x + (if strongSpaces: 100 - tok.strongSpaceA.int*10 else: 0)
  877. case tok.tokType
  878. of tkOpr:
  879. let L = tok.ident.s.len
  880. let relevantChar = tok.ident.s[0]
  881. # arrow like?
  882. if L > 1 and tok.ident.s[L-1] == '>' and
  883. tok.ident.s[L-2] in {'-', '~', '='}: return considerStrongSpaces(1)
  884. template considerAsgn(value: untyped) =
  885. result = if tok.ident.s[L-1] == '=': 1 else: value
  886. case relevantChar
  887. of '$', '^': considerAsgn(10)
  888. of '*', '%', '/', '\\': considerAsgn(9)
  889. of '~': result = 8
  890. of '+', '-', '|': considerAsgn(8)
  891. of '&': considerAsgn(7)
  892. of '=', '<', '>', '!': result = 5
  893. of '.': considerAsgn(6)
  894. of '?': result = 2
  895. else: considerAsgn(2)
  896. of tkDiv, tkMod, tkShl, tkShr: result = 9
  897. of tkIn, tkNotin, tkIs, tkIsnot, tkOf, tkAs: result = 5
  898. of tkDotDot: result = 6
  899. of tkAnd: result = 4
  900. of tkOr, tkXor, tkPtr, tkRef: result = 3
  901. else: return -10
  902. result = considerStrongSpaces(result)
  903. proc newlineFollows*(L: TLexer): bool =
  904. var pos = L.bufpos
  905. while true:
  906. case L.buf[pos]
  907. of ' ', '\t':
  908. inc(pos)
  909. of CR, LF:
  910. result = true
  911. break
  912. of '#':
  913. inc(pos)
  914. if L.buf[pos] == '#': inc(pos)
  915. if L.buf[pos] != '[': return true
  916. else:
  917. break
  918. proc skipMultiLineComment(L: var TLexer; tok: var TToken; start: int;
  919. isDoc: bool) =
  920. var pos = start
  921. var toStrip = 0
  922. tokenBegin(tok, pos)
  923. # detect the amount of indentation:
  924. if isDoc:
  925. toStrip = getColNumber(L, pos)
  926. while L.buf[pos] == ' ': inc pos
  927. if L.buf[pos] in {CR, LF}:
  928. pos = handleCRLF(L, pos)
  929. toStrip = 0
  930. while L.buf[pos] == ' ':
  931. inc pos
  932. inc toStrip
  933. var nesting = 0
  934. while true:
  935. case L.buf[pos]
  936. of '#':
  937. if isDoc:
  938. if L.buf[pos+1] == '#' and L.buf[pos+2] == '[':
  939. inc nesting
  940. tok.literal.add '#'
  941. elif L.buf[pos+1] == '[':
  942. inc nesting
  943. inc pos
  944. of ']':
  945. if isDoc:
  946. if L.buf[pos+1] == '#' and L.buf[pos+2] == '#':
  947. if nesting == 0:
  948. tokenEndIgnore(tok, pos+2)
  949. inc(pos, 3)
  950. break
  951. dec nesting
  952. tok.literal.add ']'
  953. elif L.buf[pos+1] == '#':
  954. if nesting == 0:
  955. tokenEndIgnore(tok, pos+1)
  956. inc(pos, 2)
  957. break
  958. dec nesting
  959. inc pos
  960. of CR, LF:
  961. tokenEndIgnore(tok, pos)
  962. pos = handleCRLF(L, pos)
  963. # strip leading whitespace:
  964. when defined(nimpretty): tok.literal.add "\L"
  965. if isDoc:
  966. when not defined(nimpretty): tok.literal.add "\n"
  967. inc tok.iNumber
  968. var c = toStrip
  969. while L.buf[pos] == ' ' and c > 0:
  970. inc pos
  971. dec c
  972. of nimlexbase.EndOfFile:
  973. tokenEndIgnore(tok, pos)
  974. lexMessagePos(L, errGenerated, pos, "end of multiline comment expected")
  975. break
  976. else:
  977. if isDoc or defined(nimpretty): tok.literal.add L.buf[pos]
  978. inc(pos)
  979. L.bufpos = pos
  980. when defined(nimpretty):
  981. tok.commentOffsetB = L.offsetBase + pos - 1
  982. proc scanComment(L: var TLexer, tok: var TToken) =
  983. var pos = L.bufpos
  984. tok.tokType = tkComment
  985. # iNumber contains the number of '\n' in the token
  986. tok.iNumber = 0
  987. assert L.buf[pos+1] == '#'
  988. when defined(nimpretty):
  989. tok.commentOffsetA = L.offsetBase + pos - 1
  990. if L.buf[pos+2] == '[':
  991. skipMultiLineComment(L, tok, pos+3, true)
  992. return
  993. tokenBegin(tok, pos)
  994. inc(pos, 2)
  995. var toStrip = 0
  996. while L.buf[pos] == ' ':
  997. inc pos
  998. inc toStrip
  999. while true:
  1000. var lastBackslash = -1
  1001. while L.buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
  1002. if L.buf[pos] == '\\': lastBackslash = pos+1
  1003. add(tok.literal, L.buf[pos])
  1004. inc(pos)
  1005. tokenEndIgnore(tok, pos)
  1006. pos = handleCRLF(L, pos)
  1007. var indent = 0
  1008. while L.buf[pos] == ' ':
  1009. inc(pos)
  1010. inc(indent)
  1011. if L.buf[pos] == '#' and L.buf[pos+1] == '#':
  1012. tok.literal.add "\n"
  1013. inc(pos, 2)
  1014. var c = toStrip
  1015. while L.buf[pos] == ' ' and c > 0:
  1016. inc pos
  1017. dec c
  1018. inc tok.iNumber
  1019. else:
  1020. if L.buf[pos] > ' ':
  1021. L.indentAhead = indent
  1022. tokenEndIgnore(tok, pos)
  1023. break
  1024. L.bufpos = pos
  1025. when defined(nimpretty):
  1026. tok.commentOffsetB = L.offsetBase + pos - 1
  1027. proc skip(L: var TLexer, tok: var TToken) =
  1028. var pos = L.bufpos
  1029. tokenBegin(tok, pos)
  1030. tok.strongSpaceA = 0
  1031. when defined(nimpretty):
  1032. var hasComment = false
  1033. var commentIndent = L.currLineIndent
  1034. tok.commentOffsetA = L.offsetBase + pos
  1035. tok.commentOffsetB = tok.commentOffsetA
  1036. tok.line = -1
  1037. while true:
  1038. case L.buf[pos]
  1039. of ' ':
  1040. inc(pos)
  1041. inc(tok.strongSpaceA)
  1042. of '\t':
  1043. if not L.allowTabs: lexMessagePos(L, errGenerated, pos, "tabs are not allowed, use spaces instead")
  1044. inc(pos)
  1045. of CR, LF:
  1046. tokenEndPrevious(tok, pos)
  1047. pos = handleCRLF(L, pos)
  1048. var indent = 0
  1049. while true:
  1050. if L.buf[pos] == ' ':
  1051. inc(pos)
  1052. inc(indent)
  1053. elif L.buf[pos] == '#' and L.buf[pos+1] == '[':
  1054. when defined(nimpretty):
  1055. hasComment = true
  1056. if tok.line < 0:
  1057. tok.line = L.lineNumber
  1058. commentIndent = indent
  1059. skipMultiLineComment(L, tok, pos+2, false)
  1060. pos = L.bufpos
  1061. else:
  1062. break
  1063. tok.strongSpaceA = 0
  1064. when defined(nimpretty):
  1065. if L.buf[pos] == '#' and tok.line < 0: commentIndent = indent
  1066. if L.buf[pos] > ' ' and (L.buf[pos] != '#' or L.buf[pos+1] == '#'):
  1067. tok.indent = indent
  1068. L.currLineIndent = indent
  1069. break
  1070. of '#':
  1071. # do not skip documentation comment:
  1072. if L.buf[pos+1] == '#': break
  1073. when defined(nimpretty):
  1074. hasComment = true
  1075. if tok.line < 0:
  1076. tok.line = L.lineNumber
  1077. if L.buf[pos+1] == '[':
  1078. skipMultiLineComment(L, tok, pos+2, false)
  1079. pos = L.bufpos
  1080. else:
  1081. tokenBegin(tok, pos)
  1082. while L.buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
  1083. when defined(nimpretty): tok.literal.add L.buf[pos]
  1084. inc(pos)
  1085. tokenEndIgnore(tok, pos+1)
  1086. when defined(nimpretty):
  1087. tok.commentOffsetB = L.offsetBase + pos + 1
  1088. else:
  1089. break # EndOfFile also leaves the loop
  1090. tokenEndPrevious(tok, pos-1)
  1091. L.bufpos = pos
  1092. when defined(nimpretty):
  1093. if hasComment:
  1094. tok.commentOffsetB = L.offsetBase + pos - 1
  1095. tok.tokType = tkComment
  1096. tok.indent = commentIndent
  1097. proc rawGetTok*(L: var TLexer, tok: var TToken) =
  1098. template atTokenEnd() {.dirty.} =
  1099. when defined(nimsuggest):
  1100. # we attach the cursor to the last *strong* token
  1101. if tok.tokType notin weakTokens:
  1102. L.previousToken.line = tok.line.uint16
  1103. L.previousToken.col = tok.col.int16
  1104. when defined(nimsuggest):
  1105. L.cursor = CursorPosition.None
  1106. fillToken(tok)
  1107. if L.indentAhead >= 0:
  1108. tok.indent = L.indentAhead
  1109. L.currLineIndent = L.indentAhead
  1110. L.indentAhead = -1
  1111. else:
  1112. tok.indent = -1
  1113. skip(L, tok)
  1114. when defined(nimpretty):
  1115. if tok.tokType == tkComment:
  1116. L.indentAhead = L.currLineIndent
  1117. return
  1118. var c = L.buf[L.bufpos]
  1119. tok.line = L.lineNumber
  1120. tok.col = getColNumber(L, L.bufpos)
  1121. if c in SymStartChars - {'r', 'R'}:
  1122. getSymbol(L, tok)
  1123. else:
  1124. case c
  1125. of '#':
  1126. scanComment(L, tok)
  1127. of '*':
  1128. # '*:' is unfortunately a special case, because it is two tokens in
  1129. # 'var v*: int'.
  1130. if L.buf[L.bufpos+1] == ':' and L.buf[L.bufpos+2] notin OpChars:
  1131. var h = 0 !& ord('*')
  1132. endOperator(L, tok, L.bufpos+1, h)
  1133. else:
  1134. getOperator(L, tok)
  1135. of ',':
  1136. tok.tokType = tkComma
  1137. inc(L.bufpos)
  1138. of 'r', 'R':
  1139. if L.buf[L.bufpos + 1] == '\"':
  1140. inc(L.bufpos)
  1141. getString(L, tok, raw)
  1142. else:
  1143. getSymbol(L, tok)
  1144. of '(':
  1145. inc(L.bufpos)
  1146. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1147. tok.tokType = tkParDotLe
  1148. inc(L.bufpos)
  1149. else:
  1150. tok.tokType = tkParLe
  1151. when defined(nimsuggest):
  1152. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col < L.config.m.trackPos.col and
  1153. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideCon:
  1154. L.config.m.trackPos.col = tok.col.int16
  1155. of ')':
  1156. tok.tokType = tkParRi
  1157. inc(L.bufpos)
  1158. of '[':
  1159. inc(L.bufpos)
  1160. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1161. tok.tokType = tkBracketDotLe
  1162. inc(L.bufpos)
  1163. elif L.buf[L.bufpos] == ':':
  1164. tok.tokType = tkBracketLeColon
  1165. inc(L.bufpos)
  1166. else:
  1167. tok.tokType = tkBracketLe
  1168. of ']':
  1169. tok.tokType = tkBracketRi
  1170. inc(L.bufpos)
  1171. of '.':
  1172. when defined(nimsuggest):
  1173. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col+1 == L.config.m.trackPos.col and
  1174. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideSug:
  1175. tok.tokType = tkDot
  1176. L.cursor = CursorPosition.InToken
  1177. L.config.m.trackPos.col = tok.col.int16
  1178. inc(L.bufpos)
  1179. atTokenEnd()
  1180. return
  1181. if L.buf[L.bufpos+1] == ']':
  1182. tok.tokType = tkBracketDotRi
  1183. inc(L.bufpos, 2)
  1184. elif L.buf[L.bufpos+1] == '}':
  1185. tok.tokType = tkCurlyDotRi
  1186. inc(L.bufpos, 2)
  1187. elif L.buf[L.bufpos+1] == ')':
  1188. tok.tokType = tkParDotRi
  1189. inc(L.bufpos, 2)
  1190. else:
  1191. getOperator(L, tok)
  1192. of '{':
  1193. inc(L.bufpos)
  1194. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1195. tok.tokType = tkCurlyDotLe
  1196. inc(L.bufpos)
  1197. else:
  1198. tok.tokType = tkCurlyLe
  1199. of '}':
  1200. tok.tokType = tkCurlyRi
  1201. inc(L.bufpos)
  1202. of ';':
  1203. tok.tokType = tkSemiColon
  1204. inc(L.bufpos)
  1205. of '`':
  1206. tok.tokType = tkAccent
  1207. inc(L.bufpos)
  1208. of '_':
  1209. inc(L.bufpos)
  1210. if L.buf[L.bufpos] notin SymChars+{'_'}:
  1211. tok.tokType = tkSymbol
  1212. tok.ident = L.cache.getIdent("_")
  1213. else:
  1214. tok.literal = $c
  1215. tok.tokType = tkInvalid
  1216. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1217. of '\"':
  1218. # check for generalized raw string literal:
  1219. let mode = if L.bufpos > 0 and L.buf[L.bufpos-1] in SymChars: generalized else: normal
  1220. getString(L, tok, mode)
  1221. if mode == generalized:
  1222. # tkRStrLit -> tkGStrLit
  1223. # tkTripleStrLit -> tkGTripleStrLit
  1224. inc(tok.tokType, 2)
  1225. of '\'':
  1226. tok.tokType = tkCharLit
  1227. getCharacter(L, tok)
  1228. tok.tokType = tkCharLit
  1229. of '0'..'9':
  1230. getNumber(L, tok)
  1231. let c = L.buf[L.bufpos]
  1232. if c in SymChars+{'_'}:
  1233. lexMessage(L, errGenerated, "invalid token: no whitespace between number and identifier")
  1234. else:
  1235. if c in OpChars:
  1236. getOperator(L, tok)
  1237. elif c == nimlexbase.EndOfFile:
  1238. tok.tokType = tkEof
  1239. tok.indent = 0
  1240. else:
  1241. tok.literal = $c
  1242. tok.tokType = tkInvalid
  1243. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1244. inc(L.bufpos)
  1245. atTokenEnd()
  1246. proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream;
  1247. cache: IdentCache; config: ConfigRef): int =
  1248. var lex: TLexer
  1249. var tok: TToken
  1250. initToken(tok)
  1251. openLexer(lex, fileIdx, inputstream, cache, config)
  1252. var prevToken = tkEof
  1253. while tok.tokType != tkEof:
  1254. rawGetTok(lex, tok)
  1255. if tok.indent > 0 and prevToken in {tkColon, tkEquals, tkType, tkConst, tkLet, tkVar, tkUsing}:
  1256. result = tok.indent
  1257. if result > 0: break
  1258. prevToken = tok.tokType
  1259. closeLexer(lex)
  1260. proc getPrecedence*(ident: PIdent): int =
  1261. ## assumes ident is binary operator already
  1262. var tok: TToken
  1263. initToken(tok)
  1264. tok.ident = ident
  1265. tok.tokType =
  1266. if tok.ident.id in ord(tokKeywordLow) - ord(tkSymbol) .. ord(tokKeywordHigh) - ord(tkSymbol):
  1267. TTokType(tok.ident.id + ord(tkSymbol))
  1268. else: tkOpr
  1269. getPrecedence(tok, false)