lexer.nim 44 KB

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