antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.04k stars 3.27k forks source link

_sharedContextCache is not thread safe #4634

Open dadadong opened 4 months ago

dadadong commented 4 months ago

I am using the swift version of ANTLR4.13.1 to parse the objc code file, and I always encounter a crash. My code structure is as follows:

        let queue = OperationQueue()
        for path in paths {
            let opt = BlockOperation {
                guard let input = try? ANTLRFileStream(path) else {
                    return nil
                }
                let lexer = ObjectiveCLexer(input)
                let tokens = CommonTokenStream(lexer)
                guard let parser = try? ObjectiveCParser(tokens) else {
                    return nil
                }
                parser.setErrorHandler(BailErrorStrategy())
                guard let unit = try? parser.translationUnit(),
                      unit.exception == nil
                else {
                    return nil
                }
                // soming....
            }
            queue.addOperation(opt)
        }

Crash stack: image

dadadong commented 3 months ago

I use the following code to solve the thread-safety problem and do not know if there is a risk,any help me :)

private class OC_Parsor: ObjectiveCParser {
    private let _cache = PredictionContextCache()

    override init(_ input: TokenStream) throws {
        RuntimeMetaData.checkVersion("4.13.1", RuntimeMetaData.VERSION)
        try super.init(input)
        _interp = ParserATNSimulator(self, ObjectiveCParser._ATN, ObjectiveCParser._decisionToDFA, _cache)
    }
}