1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
|
#!/usr/bin/env ruby -w
# encoding: UTF-8
#
# = Scanner.rb -- The TaskJuggler III Project Management Software
#
# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
# by Chris Schlaeger <cs@taskjuggler.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
require 'stringio'
require 'strscan'
require 'taskjuggler/UTF8String'
require 'taskjuggler/TextParser/SourceFileInfo'
require 'taskjuggler/TextParser/MacroTable'
class TaskJuggler::TextParser
# The Scanner class is an abstract text scanner with support for nested
# include files and text macros. The tokenizer will operate on rules that
# must be provided by a derived class. The scanner is modal. Each mode
# operates only with the subset of token patterns that are assigned to the
# current mode. The current line is tracked accurately and can be used for
# error reporting. The scanner can operate on Strings or Files.
class Scanner
class MacroStackEntry
attr_reader :macro, :args, :text, :endPos
def initialize(macro, args, text, endPos)
@macro = macro
@args = args
@text = text
@endPos = endPos
end
end
# This class is used to handle the low-level input operations. It knows
# whether it deals with a text buffer or a file and abstracts this to the
# Scanner. For each nested file the scanner puts a StreamHandle on the
# stack while the file is scanned. With this stack the scanner can resume
# the processing of the enclosing file once the included files have been
# completely processed.
class StreamHandle
attr_reader :fileName, :macroStack
def initialize(log, textScanner)
@log = log
@textScanner = textScanner
@fileName = nil
@stream = nil
@line = nil
@endPos = 1
@scanner = nil
@wrapped = false
@macroStack = []
@nextMacroEnd = nil
end
def error(id, message)
@textScanner.error(id, message)
end
def close
@stream = nil
end
# Inject the String _text_ into the input stream at the current cursor
# position.
def injectText(text, callLength)
# Remove the macro call from the end of the already parsed input.
preCall = @scanner.pre_match[0..-(callLength + 1)]
# Store the end position of the inserted macro in bytes.
@nextMacroEnd = preCall.bytesize + text.bytesize
# Compose the new @line from the cleaned input, the injected text and
# the remainer of the old @line.
@line = preCall + text + @scanner.post_match
# Start the StringScanner again at the first character of the injected
# text.
@scanner.string = @line
@scanner.pos = preCall.bytesize
end
def injectMacro(macro, args, text, callLength)
injectText(text, callLength)
# Simple detection for recursive macro calls.
return false if @macroStack.length > 20
@macroStack << MacroStackEntry.new(macro, args, text, @nextMacroEnd)
true
end
def readyNextLine
# We read the file line by line with gets(). If we don't have a line
# yet or we've reached the end of a line, we get the next one.
if @scanner.nil? || @scanner.eos?
if (@line = @stream.gets)
# Update activity meter about every 1024 lines.
@log.activity if (@stream.lineno & 0x3FF) == 0
else
# We've reached the end of the current file.
@scanner = nil
return false
end
@scanner = StringScanner.new(@line)
@wrapped = @line[-1] == ?\n
end
true
end
def scan(re)
@scanner.scan(re)
end
def cleanupMacroStack
if @nextMacroEnd
pos = @scanner.pos
while @nextMacroEnd && @nextMacroEnd < pos
@macroStack.pop
@nextMacroEnd = @macroStack.empty? ? nil : @macroStack.last.endPos
end
end
end
def peek(n)
@scanner ? @scanner.peek(n) : nil
end
def eof?
@stream.eof? && @scanner.eos?
end
def dirname
@fileName ? File.dirname(@fileName) : ''
end
# Return the number of the currently processed line.
def lineNo
# The IO object counts the lines for us by counting the gets() calls.
currentLine = @stream && @scanner ? @stream.lineno : 1
# If we've just read the LF, we have to add 1. The LF can only be the
# last character of the line.
currentLine += 1 if @wrapped && @line && @scanner && @scanner.eos?
currentLine
end
# Return the already processed part of the current line.
def line
return '' unless @line
(@scanner.pre_match || '') + (@scanner.matched || '')
end
end
# Specialized version of StreamHandle for operations on files.
class FileStreamHandle < StreamHandle
attr_reader :fileName
def initialize(fileName, log, textScanner)
super(log, textScanner)
@fileName = fileName.dup
data = (fileName == '.' ? $stdin : File.new(@fileName, 'r')).read
begin
@stream = StringIO.new(data.forceUTF8Encoding)
rescue
error('fileEncoding', $!.message)
end
@log.msg { "Parsing file #{@fileName} ..." }
@log.startProgressMeter("Reading file #{fileName}")
end
def close
@stream.close unless @stream == $stdin
super
end
end
# Specialized version of StreamHandle for operations on Strings.
class BufferStreamHandle < StreamHandle
def initialize(buffer, log, textScanner)
super(log, textScanner)
begin
@stream = StringIO.new(buffer)
rescue
error('bufferEncoding', $!.message)
end
#@log.msg { "Parsing buffer #{buffer[0, 20]} ..." }
end
end
# Create a new instance of Scanner. _masterFile_ must be a String that
# either contains the name of the file to start with or the text itself.
# _messageHandler_ is a MessageHandler that is used for error messages.
# _log_ is a Log to report progress and status.
def initialize(masterFile, log, tokenPatterns, defaultMode)
@masterFile = masterFile
@messageHandler = TaskJuggler::MessageHandlerInstance.instance
@log = log
# This table contains all macros that may be expanded when found in the
# text.
@macroTable = MacroTable.new
# The currently processed IO object.
@cf = nil
# This Array stores the currently processed nested files. It's an Array
# of Arrays. The nested Array consists of 2 elements, the IO object and
# the @tokenBuffer.
@fileStack = []
# This flag is set if we have reached the end of a file. Since we will
# only know when the next new token is requested that the file is really
# done now, we have to use this flag.
@finishLastFile = false
# True if the scanner operates on a buffer.
@fileNameIsBuffer = false
# A SourceFileInfo of the start of the currently processed token.
@startOfToken = nil
# Line number correction for error messages.
@lineDelta = 0
# Lists of regexps that describe the detectable tokens. The Arrays are
# grouped by mode.
@patternsByMode = { }
# The currently active scanner mode.
@scannerMode = nil
# The mode that the scanner is in at the start and end of file
@defaultMode = defaultMode
# Points to the currently active pattern set as defined by the mode.
@activePatterns = nil
tokenPatterns.each do |pat|
type = pat[0]
regExp = pat[1]
mode = pat[2] || :tjp
postProc = pat[3]
addPattern(type, regExp, mode, postProc)
end
self.mode = defaultMode
end
# Add a new pattern to the scanner. _type_ is either nil for tokens that
# will be ignored, or some identifier that will be returned with each
# token of this type. _regExp_ is the RegExp that describes the token.
# _mode_ identifies the scanner mode where the pattern is active. If it's
# only a single mode, _mode_ specifies the mode directly. For multiple
# modes, it's an Array of modes. _postProc_ is a method reference. This
# method is called after the token has been detected. The method gets the
# type and the matching String and returns them again in an Array.
def addPattern(type, regExp, mode, postProc = nil)
if mode.is_a?(Array)
mode.each do |m|
# The pattern is active in multiple modes
@patternsByMode[m] = [] unless @patternsByMode.include?(m)
@patternsByMode[m] << [ type, regExp, postProc ]
end
else
# The pattern is only active in one specific mode.
@patternsByMode[mode] = [] unless @patternsByMode.include?(mode)
@patternsByMode[mode] << [ type, regExp, postProc ]
end
end
# Switch the parser to another mode. The scanner will then only detect
# patterns of that _newMode_.
def mode=(newMode)
#puts "**** New mode: #{newMode}"
@activePatterns = @patternsByMode[newMode]
raise "Undefined mode #{newMode}" unless @activePatterns
@scannerMode = newMode
end
# Start the processing. If _fileNameIsBuffer_ is true, we operate on a
# String, else on a File.
def open(fileNameIsBuffer = false)
@fileNameIsBuffer = fileNameIsBuffer
if fileNameIsBuffer
@fileStack = [ [ @cf = BufferStreamHandle.new(@masterFile, @log, self),
nil, nil ] ]
else
begin
@fileStack = [ [ @cf = FileStreamHandle.new(@masterFile, @log, self),
nil, nil ] ]
rescue IOError, SystemCallError
error('open_file', "Cannot open file #{@masterFile}: #{$!}")
end
end
@masterPath = @cf.dirname + '/'
@tokenBuffer = nil
end
# Finish processing and reset all data structures.
def close
unless @fileNameIsBuffer
@log.startProgressMeter("Reading file #{@masterFile}")
@log.stopProgressMeter
end
@fileStack = []
@cf = @tokenBuffer = nil
end
# Continue processing with a new file specified by _includeFileName_. When
# this file is finished, we will continue in the old file after the
# location where we started with the new file. The method returns the full
# qualified name of the included file.
def include(includeFileName, sfi, &block)
if includeFileName[0] != '/'
pathOfCallingFile = @fileStack.last[0].dirname
path = pathOfCallingFile.empty? ? '' : pathOfCallingFile + '/'
# If the included file is not an absolute name, we interpret the file
# name relative to the including file.
includeFileName = path + includeFileName
end
# Try to dectect recursive inclusions. This will not work if files are
# accessed via filesystem links.
@fileStack.each do |entry|
if includeFileName == entry[0].fileName
error('include_recursion',
"Recursive inclusion of #{includeFileName} detected", sfi)
end
end
# Save @tokenBuffer in the record of the parent file.
@fileStack.last[1] = @tokenBuffer unless @fileStack.empty?
@tokenBuffer = nil
@finishLastFile = false
# Open the new file and push the handle on the @fileStack.
begin
@fileStack << [ (@cf = FileStreamHandle.new(includeFileName, @log,
self)), nil, block ]
@log.msg { "Parsing file #{includeFileName}" }
rescue StandardError
error('bad_include', "Cannot open include file #{includeFileName}", sfi)
end
# Return the name of the included file.
includeFileName
end
# Return SourceFileInfo for the current processing prosition.
def sourceFileInfo
@cf ? SourceFileInfo.new(fileName, @cf.lineNo - @lineDelta, 0) :
SourceFileInfo.new(@masterFile, 0, 0)
end
# Return the name of the currently processed file. If we are working on a
# text buffer, the text will be returned.
def fileName
@cf ? @cf.fileName : @masterFile
end
def lineNo # :nodoc:
@cf ? @cf.lineNo : 0
end
def columnNo # :nodoc:
0
end
def line # :nodoc:
@cf ? @cf.line : 0
end
# Return the next token from the input stream. The result is an Array with
# 3 entries: the token type, the token String and the SourceFileInfo where
# the token started.
def nextToken
# If we have a pushed-back token, return that first.
unless @tokenBuffer.nil?
res = @tokenBuffer
@tokenBuffer = nil
return res
end
if @finishLastFile
# The previously processed file has now really been processed to
# completion. Close it and remove the corresponding entry from the
# @fileStack.
@finishLastFile = false
#@log.msg { "Completed file #{@cf.fileName}" }
# If we have a block to be executed on EOF, we call it now.
onEof = @fileStack.last[2]
onEof.call if onEof
@cf.close if @cf
@fileStack.pop
if @fileStack.empty?
# We are done with the top-level file now.
@cf = @tokenBuffer = nil
@finishLastFile = true
return [ :endOfText, '<EOT>', @startOfToken ]
else
# Continue parsing the file that included the current file.
@cf, tokenBuffer = @fileStack.last
@log.msg { "Parsing file #{@cf.fileName} ..." }
# If we have a left over token from previously processing this file,
# return it now.
if tokenBuffer
@finishLastFile = true if tokenBuffer[0] == :eof
return tokenBuffer
end
end
end
scanToken
end
# Return a token to retrieve it with the next nextToken() call again. Only 1
# token can be returned before the next nextToken() call.
def returnToken(token)
#@log.msg { "-> Returning Token: [#{token[0]}][#{token[1]}]" }
unless @tokenBuffer.nil?
$stderr.puts @tokenBuffer
raise "Fatal Error: Cannot return more than 1 token in a row"
end
@tokenBuffer = token
end
# Add a Macro to the macro translation table.
def addMacro(macro)
@macroTable.add(macro)
end
# Return true if the Macro _name_ has been added already.
def macroDefined?(name)
@macroTable.include?(name)
end
# Expand a macro and inject it into the input stream. _prefix_ is any
# string that was found right before the macro call. We have to inject it
# before the expanded macro. _args_ is an Array of Strings. The first is
# the macro name, the rest are the parameters. _callLength_ is the number
# of characters for the complete macro call "${...}".
def expandMacro(prefix, args, callLength)
# Get the expanded macro from the @macroTable.
macro, text = @macroTable.resolve(args, sourceFileInfo)
# If the expanded macro is empty, we can ignore it.
return if text == ''
unless macro && text
error('undefined_macro', "Undefined macro '#{args[0]}' called")
end
unless @cf.injectMacro(macro, args, prefix + text, callLength)
error('macro_stack_overflow', "Too many nested macro calls.")
end
end
# Call this function to report any errors related to the parsed input.
def error(id, text, sfi = nil, data = nil)
message(:error, id, text, sfi, data)
end
def warning(id, text, sfi = nil, data = nil)
message(:warning, id, text, sfi, data)
end
private
def scanToken
@startOfToken = sourceFileInfo
begin
match = nil
loop do
# First make sure that the line buffer has been filled and we have a
# line to parse.
unless @cf.readyNextLine
if @scannerMode != @defaultMode
# The stream resets the line number to 1. Since we still
# know the start of the token, we setup @lineDelta so that
# sourceFileInfo() returns the proper line number.
@lineDelta = -(@startOfToken.lineNo - 1)
error('runaway_token',
"Unterminated token starting at line #{@startOfToken}")
end
# We've found the end of an input file. Return a special token
# that describes the end of a file.
@finishLastFile = true
return [ :eof, '<END>', @startOfToken ]
end
@activePatterns.each do |type, re, postProc|
if (match = @cf.scan(re))
#raise "#{re} matches empty string" if match.empty?
# If we have a post processing method, call it now. It may modify
# the type or the found token String.
type, match = postProc.call(type, match) if postProc
break if type.nil? # Ignore certain tokens with nil type.
@cf.cleanupMacroStack
return [ type, match, @startOfToken ]
end
end
if match.nil?
# If we haven't found a match, we either hit EOF or a token we did
# not expect.
if @cf.eof?
error('unexpected_eof',
"Unexpected end of file found")
else
error('no_token_match',
"Unexpected characters found: '#{@cf.peek(10)}...'")
end
else
# Remove completely scanned expanded macros from stack.
@cf.cleanupMacroStack
end
end
rescue ArgumentError
# This is triggered by StringScanner.scan, but we don't want to put
# the block in the inner loops for performance reasons.
error('scan_encoding_error', $!.message)
end
end
def message(type, id, text, sfi, data)
unless text.empty?
line = @cf ? @cf.line : nil
sfi ||= sourceFileInfo
if @cf && !@cf.macroStack.empty?
@messageHandler.info('macro_stack', 'Macro call history:', nil)
@cf.macroStack.reverse_each do |entry|
macro = entry.macro
args = entry.args[1..-1]
args.collect! { |a| '"' + a + '"' }
@messageHandler.info('macro_stack',
" ${#{macro.name}#{args.empty? ? '' : ' '}" +
"#{args.join(' ')}}",
macro.sourceFileInfo)
end
end
case type
when :error
@messageHandler.error(id, text, sfi, line, data)
when :warning
@messageHandler.warning(id, text, sfi, line, data)
else
raise "Unknown message type #{type}"
end
end
end
end
end
|