/// <summary> /// Generates a program and a derived string table from the /// contents of a string. /// </summary> /// <param name="text">The source code of the program.</param> /// <param name="fileName">The file name to assign to the compiled /// results.</param> /// <param name="program">On return, contains the compiled /// program.</param> /// <param name="stringTable">On return, contains the string table /// generated from the source code.</param> /// <returns>The status of the compilation.</returns> /// <exception cref="ParseException">Thrown when a parse error /// occurs during compilation.</exception> public static Status CompileString(string text, string fileName, out Program program, out IDictionary <string, StringInfo> stringTable) { ICharStream input = CharStreams.fromstring(text); YarnSpinnerLexer lexer = new YarnSpinnerLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); YarnSpinnerParser parser = new YarnSpinnerParser(tokens); // turning off the normal error listener and using ours parser.RemoveErrorListeners(); parser.AddErrorListener(ParserErrorListener.Instance); lexer.RemoveErrorListeners(); lexer.AddErrorListener(LexerErrorListener.Instance); IParseTree tree; try { tree = parser.dialogue(); } catch (ParseException e) { var tokenStringList = new List <string>(); tokens.Reset(); foreach (var token in tokens.GetTokens()) { tokenStringList.Add($"{token.Line}:{token.Column} {YarnSpinnerLexer.DefaultVocabulary.GetDisplayName(token.Type)} \"{token.Text}\""); } throw new ParseException($"{e.Message}\n\nTokens:\n{string.Join("\n", tokenStringList)}"); } Compiler compiler = new Compiler(fileName); compiler.Compile(tree); program = compiler.Program; stringTable = compiler.StringTable; if (compiler.containsImplicitStringTags) { return(Status.SucceededUntaggedStrings); } else { return(Status.Succeeded); } }
private static IParseTree ParseSyntaxTree(CompilationJob.File file) { ICharStream input = CharStreams.fromstring(file.Source); YarnSpinnerLexer lexer = new YarnSpinnerLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); YarnSpinnerParser parser = new YarnSpinnerParser(tokens); // turning off the normal error listener and using ours parser.RemoveErrorListeners(); parser.AddErrorListener(ParserErrorListener.Instance); lexer.RemoveErrorListeners(); lexer.AddErrorListener(LexerErrorListener.Instance); IParseTree tree; try { tree = parser.dialogue(); } catch (ParseException e) { #if DEBUG var tokenStringList = new List <string>(); tokens.Reset(); foreach (var token in tokens.GetTokens()) { tokenStringList.Add($"{token.Line}:{token.Column} {YarnSpinnerLexer.DefaultVocabulary.GetDisplayName(token.Type)} \"{token.Text}\""); } throw new ParseException(e.Context, $"{e.Message}\n\nTokens:\n{string.Join("\n", tokenStringList)}", file.FileName); #else throw new ParseException(e.Context, e.Message, file.FileName); #endif // DEBUG } return(tree); }