Compiler/lexical analyzer: Difference between revisions

Content added Content deleted
m (→‎{{header|C++}}: fix warning)
(Added missing “next()” for operators with two characters (<=, >=, ==, !=, &&, ||).)
Line 6,322: Line 6,322:


type
type

TokenKind* = enum
TokenKind* = enum
tokMult = "Op_multiply", tokDiv = "Op_divide", tokMod = "Op_mod",
tokMult = "Op_multiply", tokDiv = "Op_divide", tokMod = "Op_mod",
Line 6,337: Line 6,338:
tokString = "String"
tokString = "String"
tokEnd = "End_of_input"
tokEnd = "End_of_input"

Token* = object
Token* = object
ln*, col*: int
ln*, col*: int
Line 6,345: Line 6,347:
of tokString: stringVal*: string
of tokString: stringVal*: string
else: discard
else: discard

Lexer* = object
Lexer* = object
input: string
input: string
pos: int
pos: int
ln, col: int
ln, col: int

LexicalError* = object of CatchableError
LexicalError* = object of CatchableError
ln*, col*: int
ln*, col*: int
Line 6,420: Line 6,424:
of '>':
of '>':
next()
next()
if current() == '=': result = Token(kind: tokGreaterEq)
if current() == '=':
else: result = Token(kind: tokGreater)
result = Token(kind: tokGreaterEq)
next()
else:
result = Token(kind: tokGreater)
of '=':
of '=':
next()
next()
if current() == '=': result = Token(kind: tokEq)
if current() == '=':
else: result = Token(kind: tokAssign)
result = Token(kind: tokEq)
next()
else:
result = Token(kind: tokAssign)
of '!':
of '!':
next()
next()
if current() == '=': result = Token(kind: tokNotEq)
if current() == '=':
else: result = Token(kind: tokNot)
result = Token(kind: tokNotEq)
next()
else:
result = Token(kind: tokNot)
of '&':
of '&':
next()
next()
if current() == '&': result = Token(kind: tokAnd)
if current() == '&':
result = Token(kind: tokAnd)
else: lexer.error("'&&' expected")
next()
else:
lexer.error("'&&' expected")
of '|':
of '|':
next()
next()
if current() == '|': result = Token(kind: tokOr)
if current() == '|':
result = Token(kind: tokOr)
else: lexer.error("'||' expected")
next()
else:
lexer.error("'||' expected")
of '(': result = Token(kind: tokLPar); next()
of '(': result = Token(kind: tokLPar); next()
of ')': result = Token(kind: tokRPar); next()
of ')': result = Token(kind: tokRPar); next()