lexer.nim 43 KB

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