lexer.nim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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. t.literal.add(replacementChar)
  274. inc(L.bufpos)
  275. template eatChar(L: var TLexer, t: var TToken) =
  276. t.literal.add(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. tok.literal.add(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. tok.literal.add('_')
  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. tok.literal.add(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. t.literal.add(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. t.literal.add(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(OverflowDefect, "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(OverflowDefect, "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 OverflowDefect, RangeDefect:
  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. tok.literal.add('\L')
  630. inc(L.bufpos)
  631. of 'p', 'P':
  632. if tok.tokType == tkCharLit:
  633. lexMessage(L, errGenerated, "\\p not allowed in character literal")
  634. tok.literal.add(L.config.target.tnl)
  635. inc(L.bufpos)
  636. of 'r', 'R', 'c', 'C':
  637. tok.literal.add(CR)
  638. inc(L.bufpos)
  639. of 'l', 'L':
  640. tok.literal.add(LF)
  641. inc(L.bufpos)
  642. of 'f', 'F':
  643. tok.literal.add(FF)
  644. inc(L.bufpos)
  645. of 'e', 'E':
  646. tok.literal.add(ESC)
  647. inc(L.bufpos)
  648. of 'a', 'A':
  649. tok.literal.add(BEL)
  650. inc(L.bufpos)
  651. of 'b', 'B':
  652. tok.literal.add(BACKSPACE)
  653. inc(L.bufpos)
  654. of 'v', 'V':
  655. tok.literal.add(VT)
  656. inc(L.bufpos)
  657. of 't', 'T':
  658. tok.literal.add('\t')
  659. inc(L.bufpos)
  660. of '\'', '\"':
  661. tok.literal.add(L.buf[L.bufpos])
  662. inc(L.bufpos)
  663. of '\\':
  664. tok.literal.add('\\')
  665. inc(L.bufpos)
  666. of 'x', 'X':
  667. inc(L.bufpos)
  668. var xi = 0
  669. handleHexChar(L, xi, 1)
  670. handleHexChar(L, xi, 2)
  671. tok.literal.add(chr(xi))
  672. of 'u', 'U':
  673. if tok.tokType == tkCharLit:
  674. lexMessage(L, errGenerated, "\\u not allowed in character literal")
  675. inc(L.bufpos)
  676. var xi = 0
  677. if L.buf[L.bufpos] == '{':
  678. inc(L.bufpos)
  679. var start = L.bufpos
  680. while L.buf[L.bufpos] != '}':
  681. handleHexChar(L, xi, 0)
  682. if start == L.bufpos:
  683. lexMessage(L, errGenerated,
  684. "Unicode codepoint cannot be empty")
  685. inc(L.bufpos)
  686. if xi > 0x10FFFF:
  687. let hex = ($L.buf)[start..L.bufpos-2]
  688. lexMessage(L, errGenerated,
  689. "Unicode codepoint must be lower than 0x10FFFF, but was: " & hex)
  690. else:
  691. handleHexChar(L, xi, 1)
  692. handleHexChar(L, xi, 2)
  693. handleHexChar(L, xi, 3)
  694. handleHexChar(L, xi, 4)
  695. addUnicodeCodePoint(tok.literal, xi)
  696. of '0'..'9':
  697. if matchTwoChars(L, '0', {'0'..'9'}):
  698. lexMessage(L, warnOctalEscape)
  699. var xi = 0
  700. handleDecChars(L, xi)
  701. if (xi <= 255): tok.literal.add(chr(xi))
  702. else: lexMessage(L, errGenerated, "invalid character constant")
  703. else: lexMessage(L, errGenerated, "invalid character constant")
  704. proc newString(s: cstring, len: int): string =
  705. ## XXX, how come there is no support for this?
  706. result = newString(len)
  707. for i in 0..<len:
  708. result[i] = s[i]
  709. proc handleCRLF(L: var TLexer, pos: int): int =
  710. template registerLine =
  711. let col = L.getColNumber(pos)
  712. if col > MaxLineLength:
  713. lexMessagePos(L, hintLineTooLong, pos)
  714. case L.buf[pos]
  715. of CR:
  716. registerLine()
  717. result = nimlexbase.handleCR(L, pos)
  718. of LF:
  719. registerLine()
  720. result = nimlexbase.handleLF(L, pos)
  721. else: result = pos
  722. type
  723. StringMode = enum
  724. normal,
  725. raw,
  726. generalized
  727. proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
  728. var pos = L.bufpos
  729. var line = L.lineNumber # save linenumber for better error message
  730. tokenBegin(tok, pos - ord(mode == raw))
  731. inc pos # skip "
  732. if L.buf[pos] == '\"' and L.buf[pos+1] == '\"':
  733. tok.tokType = tkTripleStrLit # long string literal:
  734. inc(pos, 2) # skip ""
  735. # skip leading newline:
  736. if L.buf[pos] in {' ', '\t'}:
  737. var newpos = pos+1
  738. while L.buf[newpos] in {' ', '\t'}: inc newpos
  739. if L.buf[newpos] in {CR, LF}: pos = newpos
  740. pos = handleCRLF(L, pos)
  741. while true:
  742. case L.buf[pos]
  743. of '\"':
  744. if L.buf[pos+1] == '\"' and L.buf[pos+2] == '\"' and
  745. L.buf[pos+3] != '\"':
  746. tokenEndIgnore(tok, pos+2)
  747. L.bufpos = pos + 3 # skip the three """
  748. break
  749. tok.literal.add('\"')
  750. inc(pos)
  751. of CR, LF:
  752. tokenEndIgnore(tok, pos)
  753. pos = handleCRLF(L, pos)
  754. tok.literal.add("\n")
  755. of nimlexbase.EndOfFile:
  756. tokenEndIgnore(tok, pos)
  757. var line2 = L.lineNumber
  758. L.lineNumber = line
  759. lexMessagePos(L, errGenerated, L.lineStart, "closing \"\"\" expected, but end of file reached")
  760. L.lineNumber = line2
  761. L.bufpos = pos
  762. break
  763. else:
  764. tok.literal.add(L.buf[pos])
  765. inc(pos)
  766. else:
  767. # ordinary string literal
  768. if mode != normal: tok.tokType = tkRStrLit
  769. else: tok.tokType = tkStrLit
  770. while true:
  771. var c = L.buf[pos]
  772. if c == '\"':
  773. if mode != normal and L.buf[pos+1] == '\"':
  774. inc(pos, 2)
  775. tok.literal.add('"')
  776. else:
  777. tokenEndIgnore(tok, pos)
  778. inc(pos) # skip '"'
  779. break
  780. elif c in {CR, LF, nimlexbase.EndOfFile}:
  781. tokenEndIgnore(tok, pos)
  782. lexMessage(L, errGenerated, "closing \" expected")
  783. break
  784. elif (c == '\\') and mode == normal:
  785. L.bufpos = pos
  786. getEscapedChar(L, tok)
  787. pos = L.bufpos
  788. else:
  789. tok.literal.add(c)
  790. inc(pos)
  791. L.bufpos = pos
  792. proc getCharacter(L: var TLexer, tok: var TToken) =
  793. tokenBegin(tok, L.bufpos)
  794. inc(L.bufpos) # skip '
  795. var c = L.buf[L.bufpos]
  796. case c
  797. of '\0'..pred(' '), '\'':
  798. lexMessage(L, errGenerated, "invalid character literal")
  799. tok.literal = $c
  800. of '\\': getEscapedChar(L, tok)
  801. else:
  802. tok.literal = $c
  803. inc(L.bufpos)
  804. if L.buf[L.bufpos] != '\'':
  805. lexMessage(L, errGenerated, "missing closing ' for character literal")
  806. tokenEndIgnore(tok, L.bufpos)
  807. inc(L.bufpos) # skip '
  808. proc getSymbol(L: var TLexer, tok: var TToken) =
  809. var h: Hash = 0
  810. var pos = L.bufpos
  811. tokenBegin(tok, pos)
  812. var suspicious = false
  813. while true:
  814. var c = L.buf[pos]
  815. case c
  816. of 'a'..'z', '0'..'9', '\x80'..'\xFF':
  817. h = h !& ord(c)
  818. inc(pos)
  819. of 'A'..'Z':
  820. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  821. h = h !& ord(c)
  822. inc(pos)
  823. suspicious = true
  824. of '_':
  825. if L.buf[pos+1] notin SymChars:
  826. lexMessage(L, errGenerated, "invalid token: trailing underscore")
  827. break
  828. inc(pos)
  829. suspicious = true
  830. else: break
  831. tokenEnd(tok, pos-1)
  832. h = !$h
  833. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  834. if (tok.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
  835. (tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
  836. tok.tokType = tkSymbol
  837. else:
  838. tok.tokType = TTokType(tok.ident.id + ord(tkSymbol))
  839. if suspicious and {optStyleHint, optStyleError} * L.config.globalOptions != {}:
  840. lintReport(L.config, getLineInfo(L), tok.ident.s.normalize, tok.ident.s)
  841. L.bufpos = pos
  842. proc endOperator(L: var TLexer, tok: var TToken, pos: int,
  843. hash: Hash) {.inline.} =
  844. var h = !$hash
  845. tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  846. if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr
  847. else: tok.tokType = TTokType(tok.ident.id - oprLow + ord(tkColon))
  848. L.bufpos = pos
  849. proc getOperator(L: var TLexer, tok: var TToken) =
  850. var pos = L.bufpos
  851. tokenBegin(tok, pos)
  852. var h: Hash = 0
  853. while true:
  854. var c = L.buf[pos]
  855. if c notin OpChars: break
  856. h = h !& ord(c)
  857. inc(pos)
  858. endOperator(L, tok, pos, h)
  859. tokenEnd(tok, pos-1)
  860. # advance pos but don't store it in L.bufpos so the next token (which might
  861. # be an operator too) gets the preceding spaces:
  862. tok.strongSpaceB = 0
  863. while L.buf[pos] == ' ':
  864. inc pos
  865. inc tok.strongSpaceB
  866. if L.buf[pos] in {CR, LF, nimlexbase.EndOfFile}:
  867. tok.strongSpaceB = -1
  868. proc getPrecedence*(tok: TToken, strongSpaces: bool): int =
  869. ## Calculates the precedence of the given token.
  870. template considerStrongSpaces(x): untyped =
  871. x + (if strongSpaces: 100 - tok.strongSpaceA.int*10 else: 0)
  872. case tok.tokType
  873. of tkOpr:
  874. let relevantChar = tok.ident.s[0]
  875. # arrow like?
  876. if tok.ident.s.len > 1 and tok.ident.s[^1] == '>' and
  877. tok.ident.s[^2] in {'-', '~', '='}: return considerStrongSpaces(1)
  878. template considerAsgn(value: untyped) =
  879. result = if tok.ident.s[^1] == '=': 1 else: value
  880. case relevantChar
  881. of '$', '^': considerAsgn(10)
  882. of '*', '%', '/', '\\': considerAsgn(9)
  883. of '~': result = 8
  884. of '+', '-', '|': considerAsgn(8)
  885. of '&': considerAsgn(7)
  886. of '=', '<', '>', '!': result = 5
  887. of '.': considerAsgn(6)
  888. of '?': result = 2
  889. else: considerAsgn(2)
  890. of tkDiv, tkMod, tkShl, tkShr: result = 9
  891. of tkIn, tkNotin, tkIs, tkIsnot, tkOf, tkAs, tkFrom: result = 5
  892. of tkDotDot: result = 6
  893. of tkAnd: result = 4
  894. of tkOr, tkXor, tkPtr, tkRef: result = 3
  895. else: return -10
  896. result = considerStrongSpaces(result)
  897. proc newlineFollows*(L: TLexer): bool =
  898. var pos = L.bufpos
  899. while true:
  900. case L.buf[pos]
  901. of ' ', '\t':
  902. inc(pos)
  903. of CR, LF:
  904. result = true
  905. break
  906. of '#':
  907. inc(pos)
  908. if L.buf[pos] == '#': inc(pos)
  909. if L.buf[pos] != '[': return true
  910. else:
  911. break
  912. proc skipMultiLineComment(L: var TLexer; tok: var TToken; start: int;
  913. isDoc: bool) =
  914. var pos = start
  915. var toStrip = 0
  916. tokenBegin(tok, pos)
  917. # detect the amount of indentation:
  918. if isDoc:
  919. toStrip = getColNumber(L, pos)
  920. while L.buf[pos] == ' ': inc pos
  921. if L.buf[pos] in {CR, LF}:
  922. pos = handleCRLF(L, pos)
  923. toStrip = 0
  924. while L.buf[pos] == ' ':
  925. inc pos
  926. inc toStrip
  927. var nesting = 0
  928. while true:
  929. case L.buf[pos]
  930. of '#':
  931. if isDoc:
  932. if L.buf[pos+1] == '#' and L.buf[pos+2] == '[':
  933. inc nesting
  934. tok.literal.add '#'
  935. elif L.buf[pos+1] == '[':
  936. inc nesting
  937. inc pos
  938. of ']':
  939. if isDoc:
  940. if L.buf[pos+1] == '#' and L.buf[pos+2] == '#':
  941. if nesting == 0:
  942. tokenEndIgnore(tok, pos+2)
  943. inc(pos, 3)
  944. break
  945. dec nesting
  946. tok.literal.add ']'
  947. elif L.buf[pos+1] == '#':
  948. if nesting == 0:
  949. tokenEndIgnore(tok, pos+1)
  950. inc(pos, 2)
  951. break
  952. dec nesting
  953. inc pos
  954. of CR, LF:
  955. tokenEndIgnore(tok, pos)
  956. pos = handleCRLF(L, pos)
  957. # strip leading whitespace:
  958. when defined(nimpretty): tok.literal.add "\L"
  959. if isDoc:
  960. when not defined(nimpretty): tok.literal.add "\n"
  961. inc tok.iNumber
  962. var c = toStrip
  963. while L.buf[pos] == ' ' and c > 0:
  964. inc pos
  965. dec c
  966. of nimlexbase.EndOfFile:
  967. tokenEndIgnore(tok, pos)
  968. lexMessagePos(L, errGenerated, pos, "end of multiline comment expected")
  969. break
  970. else:
  971. if isDoc or defined(nimpretty): tok.literal.add L.buf[pos]
  972. inc(pos)
  973. L.bufpos = pos
  974. when defined(nimpretty):
  975. tok.commentOffsetB = L.offsetBase + pos - 1
  976. proc scanComment(L: var TLexer, tok: var TToken) =
  977. var pos = L.bufpos
  978. tok.tokType = tkComment
  979. # iNumber contains the number of '\n' in the token
  980. tok.iNumber = 0
  981. assert L.buf[pos+1] == '#'
  982. when defined(nimpretty):
  983. tok.commentOffsetA = L.offsetBase + pos - 1
  984. if L.buf[pos+2] == '[':
  985. skipMultiLineComment(L, tok, pos+3, true)
  986. return
  987. tokenBegin(tok, pos)
  988. inc(pos, 2)
  989. var toStrip = 0
  990. while L.buf[pos] == ' ':
  991. inc pos
  992. inc toStrip
  993. while true:
  994. var lastBackslash = -1
  995. while L.buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
  996. if L.buf[pos] == '\\': lastBackslash = pos+1
  997. tok.literal.add(L.buf[pos])
  998. inc(pos)
  999. tokenEndIgnore(tok, pos)
  1000. pos = handleCRLF(L, pos)
  1001. var indent = 0
  1002. while L.buf[pos] == ' ':
  1003. inc(pos)
  1004. inc(indent)
  1005. if L.buf[pos] == '#' and L.buf[pos+1] == '#':
  1006. tok.literal.add "\n"
  1007. inc(pos, 2)
  1008. var c = toStrip
  1009. while L.buf[pos] == ' ' and c > 0:
  1010. inc pos
  1011. dec c
  1012. inc tok.iNumber
  1013. else:
  1014. if L.buf[pos] > ' ':
  1015. L.indentAhead = indent
  1016. tokenEndIgnore(tok, pos)
  1017. break
  1018. L.bufpos = pos
  1019. when defined(nimpretty):
  1020. tok.commentOffsetB = L.offsetBase + pos - 1
  1021. proc skip(L: var TLexer, tok: var TToken) =
  1022. var pos = L.bufpos
  1023. tokenBegin(tok, pos)
  1024. tok.strongSpaceA = 0
  1025. when defined(nimpretty):
  1026. var hasComment = false
  1027. var commentIndent = L.currLineIndent
  1028. tok.commentOffsetA = L.offsetBase + pos
  1029. tok.commentOffsetB = tok.commentOffsetA
  1030. tok.line = -1
  1031. while true:
  1032. case L.buf[pos]
  1033. of ' ':
  1034. inc(pos)
  1035. inc(tok.strongSpaceA)
  1036. of '\t':
  1037. if not L.allowTabs: lexMessagePos(L, errGenerated, pos, "tabs are not allowed, use spaces instead")
  1038. inc(pos)
  1039. of CR, LF:
  1040. tokenEndPrevious(tok, pos)
  1041. pos = handleCRLF(L, pos)
  1042. var indent = 0
  1043. while true:
  1044. if L.buf[pos] == ' ':
  1045. inc(pos)
  1046. inc(indent)
  1047. elif L.buf[pos] == '#' and L.buf[pos+1] == '[':
  1048. when defined(nimpretty):
  1049. hasComment = true
  1050. if tok.line < 0:
  1051. tok.line = L.lineNumber
  1052. commentIndent = indent
  1053. skipMultiLineComment(L, tok, pos+2, false)
  1054. pos = L.bufpos
  1055. else:
  1056. break
  1057. tok.strongSpaceA = 0
  1058. when defined(nimpretty):
  1059. if L.buf[pos] == '#' and tok.line < 0: commentIndent = indent
  1060. if L.buf[pos] > ' ' and (L.buf[pos] != '#' or L.buf[pos+1] == '#'):
  1061. tok.indent = indent
  1062. L.currLineIndent = indent
  1063. break
  1064. of '#':
  1065. # do not skip documentation comment:
  1066. if L.buf[pos+1] == '#': break
  1067. when defined(nimpretty):
  1068. hasComment = true
  1069. if tok.line < 0:
  1070. tok.line = L.lineNumber
  1071. if L.buf[pos+1] == '[':
  1072. skipMultiLineComment(L, tok, pos+2, false)
  1073. pos = L.bufpos
  1074. else:
  1075. tokenBegin(tok, pos)
  1076. while L.buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
  1077. when defined(nimpretty): tok.literal.add L.buf[pos]
  1078. inc(pos)
  1079. tokenEndIgnore(tok, pos+1)
  1080. when defined(nimpretty):
  1081. tok.commentOffsetB = L.offsetBase + pos + 1
  1082. else:
  1083. break # EndOfFile also leaves the loop
  1084. tokenEndPrevious(tok, pos-1)
  1085. L.bufpos = pos
  1086. when defined(nimpretty):
  1087. if hasComment:
  1088. tok.commentOffsetB = L.offsetBase + pos - 1
  1089. tok.tokType = tkComment
  1090. tok.indent = commentIndent
  1091. proc rawGetTok*(L: var TLexer, tok: var TToken) =
  1092. template atTokenEnd() {.dirty.} =
  1093. when defined(nimsuggest):
  1094. # we attach the cursor to the last *strong* token
  1095. if tok.tokType notin weakTokens:
  1096. L.previousToken.line = tok.line.uint16
  1097. L.previousToken.col = tok.col.int16
  1098. when defined(nimsuggest):
  1099. L.cursor = CursorPosition.None
  1100. fillToken(tok)
  1101. if L.indentAhead >= 0:
  1102. tok.indent = L.indentAhead
  1103. L.currLineIndent = L.indentAhead
  1104. L.indentAhead = -1
  1105. else:
  1106. tok.indent = -1
  1107. skip(L, tok)
  1108. when defined(nimpretty):
  1109. if tok.tokType == tkComment:
  1110. L.indentAhead = L.currLineIndent
  1111. return
  1112. var c = L.buf[L.bufpos]
  1113. tok.line = L.lineNumber
  1114. tok.col = getColNumber(L, L.bufpos)
  1115. if c in SymStartChars - {'r', 'R'}:
  1116. getSymbol(L, tok)
  1117. else:
  1118. case c
  1119. of '#':
  1120. scanComment(L, tok)
  1121. of '*':
  1122. # '*:' is unfortunately a special case, because it is two tokens in
  1123. # 'var v*: int'.
  1124. if L.buf[L.bufpos+1] == ':' and L.buf[L.bufpos+2] notin OpChars:
  1125. var h = 0 !& ord('*')
  1126. endOperator(L, tok, L.bufpos+1, h)
  1127. else:
  1128. getOperator(L, tok)
  1129. of ',':
  1130. tok.tokType = tkComma
  1131. inc(L.bufpos)
  1132. of 'r', 'R':
  1133. if L.buf[L.bufpos + 1] == '\"':
  1134. inc(L.bufpos)
  1135. getString(L, tok, raw)
  1136. else:
  1137. getSymbol(L, tok)
  1138. of '(':
  1139. inc(L.bufpos)
  1140. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1141. tok.tokType = tkParDotLe
  1142. inc(L.bufpos)
  1143. else:
  1144. tok.tokType = tkParLe
  1145. when defined(nimsuggest):
  1146. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col < L.config.m.trackPos.col and
  1147. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideCon:
  1148. L.config.m.trackPos.col = tok.col.int16
  1149. of ')':
  1150. tok.tokType = tkParRi
  1151. inc(L.bufpos)
  1152. of '[':
  1153. inc(L.bufpos)
  1154. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1155. tok.tokType = tkBracketDotLe
  1156. inc(L.bufpos)
  1157. elif L.buf[L.bufpos] == ':':
  1158. tok.tokType = tkBracketLeColon
  1159. inc(L.bufpos)
  1160. else:
  1161. tok.tokType = tkBracketLe
  1162. of ']':
  1163. tok.tokType = tkBracketRi
  1164. inc(L.bufpos)
  1165. of '.':
  1166. when defined(nimsuggest):
  1167. if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col+1 == L.config.m.trackPos.col and
  1168. tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideSug:
  1169. tok.tokType = tkDot
  1170. L.cursor = CursorPosition.InToken
  1171. L.config.m.trackPos.col = tok.col.int16
  1172. inc(L.bufpos)
  1173. atTokenEnd()
  1174. return
  1175. if L.buf[L.bufpos+1] == ']':
  1176. tok.tokType = tkBracketDotRi
  1177. inc(L.bufpos, 2)
  1178. elif L.buf[L.bufpos+1] == '}':
  1179. tok.tokType = tkCurlyDotRi
  1180. inc(L.bufpos, 2)
  1181. elif L.buf[L.bufpos+1] == ')':
  1182. tok.tokType = tkParDotRi
  1183. inc(L.bufpos, 2)
  1184. else:
  1185. getOperator(L, tok)
  1186. of '{':
  1187. inc(L.bufpos)
  1188. if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
  1189. tok.tokType = tkCurlyDotLe
  1190. inc(L.bufpos)
  1191. else:
  1192. tok.tokType = tkCurlyLe
  1193. of '}':
  1194. tok.tokType = tkCurlyRi
  1195. inc(L.bufpos)
  1196. of ';':
  1197. tok.tokType = tkSemiColon
  1198. inc(L.bufpos)
  1199. of '`':
  1200. tok.tokType = tkAccent
  1201. inc(L.bufpos)
  1202. of '_':
  1203. inc(L.bufpos)
  1204. if L.buf[L.bufpos] notin SymChars+{'_'}:
  1205. tok.tokType = tkSymbol
  1206. tok.ident = L.cache.getIdent("_")
  1207. else:
  1208. tok.literal = $c
  1209. tok.tokType = tkInvalid
  1210. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1211. of '\"':
  1212. # check for generalized raw string literal:
  1213. let mode = if L.bufpos > 0 and L.buf[L.bufpos-1] in SymChars: generalized else: normal
  1214. getString(L, tok, mode)
  1215. if mode == generalized:
  1216. # tkRStrLit -> tkGStrLit
  1217. # tkTripleStrLit -> tkGTripleStrLit
  1218. inc(tok.tokType, 2)
  1219. of '\'':
  1220. tok.tokType = tkCharLit
  1221. getCharacter(L, tok)
  1222. tok.tokType = tkCharLit
  1223. of '0'..'9':
  1224. getNumber(L, tok)
  1225. let c = L.buf[L.bufpos]
  1226. if c in SymChars+{'_'}:
  1227. lexMessage(L, errGenerated, "invalid token: no whitespace between number and identifier")
  1228. else:
  1229. if c in OpChars:
  1230. getOperator(L, tok)
  1231. elif c == nimlexbase.EndOfFile:
  1232. tok.tokType = tkEof
  1233. tok.indent = 0
  1234. else:
  1235. tok.literal = $c
  1236. tok.tokType = tkInvalid
  1237. lexMessage(L, errGenerated, "invalid token: " & c & " (\\" & $(ord(c)) & ')')
  1238. inc(L.bufpos)
  1239. atTokenEnd()
  1240. proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream;
  1241. cache: IdentCache; config: ConfigRef): int =
  1242. var lex: TLexer
  1243. var tok: TToken
  1244. initToken(tok)
  1245. openLexer(lex, fileIdx, inputstream, cache, config)
  1246. var prevToken = tkEof
  1247. while tok.tokType != tkEof:
  1248. rawGetTok(lex, tok)
  1249. if tok.indent > 0 and prevToken in {tkColon, tkEquals, tkType, tkConst, tkLet, tkVar, tkUsing}:
  1250. result = tok.indent
  1251. if result > 0: break
  1252. prevToken = tok.tokType
  1253. closeLexer(lex)
  1254. proc getPrecedence*(ident: PIdent): int =
  1255. ## assumes ident is binary operator already
  1256. var tok: TToken
  1257. initToken(tok)
  1258. tok.ident = ident
  1259. tok.tokType =
  1260. if tok.ident.id in ord(tokKeywordLow) - ord(tkSymbol)..ord(tokKeywordHigh) - ord(tkSymbol):
  1261. TTokType(tok.ident.id + ord(tkSymbol))
  1262. else: tkOpr
  1263. getPrecedence(tok, false)