lexer.nim 47 KB

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