lexer.nim 47 KB

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