// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // static CSharpParser ParseString (bool silent, string input, out bool partial_input) { partial_input = false; Reset (); queued_fields.Clear (); Stream s = new MemoryStream (Encoding.Default.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (!silent) Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (silent == false) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0]); parser.ErrorOutput = Report.Stderr; if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; RootContext.StatementMode = true; } else { // // Do not activate EvalCompilationUnitParserCharacter until // I have figured out all the limitations to invoke methods // in the generated classes. See repl.txt // parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter; //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; RootContext.StatementMode = false; } if (silent) Report.DisableReporting (); try { parser.parse (); } finally { if (Report.Errors != 0){ if (silent && parser.UnexpectedEOF) partial_input = true; parser.undo.ExecuteUndo (); parser = null; } if (silent) Report.EnableReporting (); } return parser; }
public void Simple () { //string content = @"class A { }"; string content = @" class Foo { void Bar () { completionList.Add (""delegate"" + sb, ""md-keyword"", GettextCatalog.GetString (""Creates anonymous delegate.""), ""delegate"" + sb + "" {"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + ""|"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent +""};""); } }" ; var stream = new MemoryStream (Encoding.UTF8.GetBytes (content)); var ctx = new CompilerContext (new CompilerSettings (), new AssertReportPrinter ()); ModuleContainer module = new ModuleContainer (ctx); var file = new SourceFile ("test", "asdfas", 0); CSharpParser parser = new CSharpParser ( new SeekableStreamReader (stream, Encoding.UTF8), new CompilationSourceFile (module, file), ctx.Report, new ParserSession ()); RootContext.ToplevelTypes = module; Location.Initialize (new List<SourceFile> { file }); parser.parse (); Assert.AreEqual (0, ctx.Report.Errors); module.Accept (new TestVisitor ()); }
public static void Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report) { var file = new CompilationSourceFile(module, sourceFile); module.AddTypeContainer(file); CSharpParser parser = new CSharpParser(reader, file, report, session); parser.parse(); }
public void Simple () { //string content = @"class A { }"; string content = @" class Foo { void Bar () { completionList.Add (""delegate"" + sb, ""md-keyword"", GettextCatalog.GetString (""Creates anonymous delegate.""), ""delegate"" + sb + "" {"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + ""|"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent +""};""); } }" ; var stream = new MemoryStream (Encoding.UTF8.GetBytes (content)); var ctx = new CompilerContext (new CompilerSettings (), new Report (new AssertReportPrinter ())); ModuleContainer module = new ModuleContainer (ctx); CSharpParser parser = new CSharpParser ( new SeekableStreamReader (stream, Encoding.UTF8), new CompilationUnit ("name", "path", 0), module); RootContext.ToplevelTypes = module; Location.AddFile (ctx.Report, "asdfas"); Location.Initialize (); parser.LocationsBag = new LocationsBag (); parser.parse (); var m = module.Types[0].Methods[0] as Method; var s = m.Block.FirstStatement; var o = s.loc.Column; module.Accept (new TestVisitor ()); }
/* /// <summary> /// Parses a file snippet; guessing what the code snippet represents (whole file, type members, block, type reference, expression). /// </summary> public AstNode ParseSnippet (string code) { // TODO: add support for parsing a part of a file throw new NotImplementedException (); } */ public DocumentationReference ParseDocumentationReference(string cref) { // see Mono.CSharp.DocumentationBuilder.HandleXrefCommon if (cref == null) throw new ArgumentNullException("cref"); // Additional symbols for < and > are allowed for easier XML typing cref = cref.Replace('{', '<').Replace('}', '>'); lock (parseLock) { errorReportPrinter = new ErrorReportPrinter(""); var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter); ctx.Settings.TabSize = 1; var reader = new SeekableStreamReader(new StringTextSource(cref)); var file = new SourceFile("", "", 0); Location.Initialize(new List<SourceFile>(new [] { file })); var module = new ModuleContainer(ctx); module.DocumentationBuilder = new DocumentationBuilder(module); var source_file = new CompilationSourceFile(module); var report = new Report(ctx, errorReportPrinter); var session = new ParserSession(); session.LocationsBag = new LocationsBag(); var parser = new Mono.CSharp.CSharpParser(reader, source_file, report, session); parser.Lexer.Line += initialLocation.Line - 1; parser.Lexer.Column += initialLocation.Column - 1; parser.Lexer.putback_char = Tokenizer.DocumentationXref; parser.Lexer.parsing_generic_declaration_doc = true; parser.parse(); if (report.Errors > 0) { // Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", // mc.GetSignatureForError (), cref); } var conversionVisitor = new ConversionVisitor(false, session.LocationsBag); var docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder); CompilerCallableEntryPoint.Reset(); return docRef; } }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // CSharpParser ParseString (ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset (); var enc = ctx.Settings.Encoding; var s = new MemoryStream (enc.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, enc); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (mode == ParseMode.ReportErrors) ctx.Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (mode == ParseMode.ReportErrors) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; source_file.DeclarationFound = false; CSharpParser parser = new CSharpParser (seekable, source_file); if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; ctx.Settings.StatementMode = true; } else { parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; ctx.Settings.StatementMode = false; } if (mode == ParseMode.GetCompletions) parser.Lexer.CompleteOnEOF = true; ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions)) old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null)); try { parser.parse (); } finally { if (ctx.Report.Errors != 0){ if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) partial_input = true; if (parser.undo != null) parser.undo.ExecuteUndo (); parser = null; } if (old_printer != null) ctx.Report.SetPrinter (old_printer); } return parser; }
// // Processes "see" or "seealso" elements from cref attribute. // void HandleXrefCommon (MemberCore mc, TypeContainer ds, XmlElement xref) { string cref = xref.GetAttribute ("cref"); // when, XmlReader, "if (cref == null)" if (!xref.HasAttribute ("cref")) return; // Nothing to be resolved the reference is marked explicitly if (cref.Length > 2 && cref [1] == ':') return; // Additional symbols for < and > are allowed for easier XML typing cref = cref.Replace ('{', '<').Replace ('}', '>'); var encoding = module.Compiler.Settings.Encoding; var s = new MemoryStream (encoding.GetBytes (cref)); SeekableStreamReader seekable = new SeekableStreamReader (s, encoding); var source_file = new CompilationSourceFile (doc_module); var report = new Report (doc_module.Compiler, new NullReportPrinter ()); var parser = new CSharpParser (seekable, source_file, report); ParsedParameters = null; ParsedName = null; ParsedBuiltinType = null; ParsedOperator = null; parser.Lexer.putback_char = Tokenizer.DocumentationXref; parser.Lexer.parsing_generic_declaration_doc = true; parser.parse (); if (report.Errors > 0) { Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", mc.GetSignatureForError (), cref); xref.SetAttribute ("cref", "!:" + cref); return; } MemberSpec member; string prefix = null; FullNamedExpression fne = null; // // Try built-in type first because we are using ParsedName as identifier of // member names on built-in types // if (ParsedBuiltinType != null && (ParsedParameters == null || ParsedName != null)) { member = ParsedBuiltinType.Type; } else { member = null; } if (ParsedName != null || ParsedOperator.HasValue) { TypeSpec type = null; string member_name = null; if (member == null) { if (ParsedOperator.HasValue) { type = mc.CurrentType; } else if (ParsedName.Left != null) { fne = ResolveMemberName (mc, ParsedName.Left); if (fne != null) { var ns = fne as Namespace; if (ns != null) { fne = ns.LookupTypeOrNamespace (mc, ParsedName.Name, ParsedName.Arity, LookupMode.Probing, Location.Null); if (fne != null) { member = fne.Type; } } else { type = fne.Type; } } } else { fne = ResolveMemberName (mc, ParsedName); if (fne == null) { type = mc.CurrentType; } else if (ParsedParameters == null) { member = fne.Type; } else if (fne.Type.MemberDefinition == mc.CurrentType.MemberDefinition) { member_name = Constructor.ConstructorName; type = fne.Type; } } } else { type = (TypeSpec) member; member = null; } if (ParsedParameters != null) { var old_printer = mc.Module.Compiler.Report.SetPrinter (new NullReportPrinter ()); foreach (var pp in ParsedParameters) { pp.Resolve (mc); } mc.Module.Compiler.Report.SetPrinter (old_printer); } if (type != null) { if (member_name == null) member_name = ParsedOperator.HasValue ? Operator.GetMetadataName (ParsedOperator.Value) : ParsedName.Name; int parsed_param_count; if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) { parsed_param_count = ParsedParameters.Count - 1; } else if (ParsedParameters != null) { parsed_param_count = ParsedParameters.Count; } else { parsed_param_count = 0; } int parameters_match = -1; do { var members = MemberCache.FindMembers (type, member_name, true); if (members != null) { foreach (var m in members) { if (ParsedName != null && m.Arity != ParsedName.Arity) continue; if (ParsedParameters != null) { IParametersMember pm = m as IParametersMember; if (pm == null) continue; if (m.Kind == MemberKind.Operator && !ParsedOperator.HasValue) continue; int i; for (i = 0; i < parsed_param_count; ++i) { var pparam = ParsedParameters[i]; if (i >= pm.Parameters.Count || pparam == null || pparam.TypeSpec != pm.Parameters.Types[i] || (pparam.Modifier & Parameter.Modifier.SignatureMask) != (pm.Parameters.FixedParameters[i].ModFlags & Parameter.Modifier.SignatureMask)) { if (i > parameters_match) { parameters_match = i; } i = -1; break; } } if (i < 0) continue; if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) { if (pm.MemberType != ParsedParameters[parsed_param_count].TypeSpec) { parameters_match = parsed_param_count + 1; continue; } } else { if (parsed_param_count != pm.Parameters.Count) continue; } } if (member != null) { Report.Warning (419, 3, mc.Location, "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched", cref, member.GetSignatureForError (), m.GetSignatureForError ()); break; } member = m; } } // Continue with parent type for nested types if (member == null) { type = type.DeclaringType; } else { type = null; } } while (type != null); if (member == null && parameters_match >= 0) { for (int i = parameters_match; i < parsed_param_count; ++i) { Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'", (i + 1).ToString (), cref); } if (parameters_match == parsed_param_count + 1) { Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref); } } } } if (member == null) { Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved", mc.GetSignatureForError (), cref); cref = "!:" + cref; } else if (member == InternalType.Namespace) { cref = "N:" + fne.GetSignatureForError (); } else { prefix = GetMemberDocHead (member); cref = prefix + member.GetSignatureForDocumentation (); } xref.SetAttribute ("cref", cref); }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset (); queued_fields.Clear (); Tokenizer.LocatedToken.Initialize (); Stream s = new MemoryStream (Encoding.Default.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (mode == ParseMode.ReportErrors) ctx.Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (mode == ParseMode.ReportErrors) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0], ctx); if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; RootContext.StatementMode = true; } else { // // Do not activate EvalCompilationUnitParserCharacter until // I have figured out all the limitations to invoke methods // in the generated classes. See repl.txt // parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter; //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; RootContext.StatementMode = false; } if (mode == ParseMode.GetCompletions) parser.Lexer.CompleteOnEOF = true; ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0) old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null)); try { parser.parse (); } finally { if (ctx.Report.Errors != 0){ if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) partial_input = true; parser.undo.ExecuteUndo (); parser = null; } if (old_printer != null) SetPrinter (old_printer); } return parser; }
public static CompilerCompilationUnit ParseFile (string[] args, Stream input, string inputFile, ReportPrinter reportPrinter) { lock (parseLock) { try { Driver d = Driver.Create (args, false, reportPrinter); if (d == null) return null; Location.AddFile (null, inputFile); Location.Initialize (); // TODO: encoding from driver SeekableStreamReader reader = new SeekableStreamReader (input, Encoding.Default); CompilerContext ctx = new CompilerContext (new ReflectionMetaImporter (), new Report (reportPrinter)); RootContext.ToplevelTypes = new ModuleCompiled (ctx, false /* isUnsafe */); CompilationUnit unit = null; try { unit = (CompilationUnit) Location.SourceFiles [0]; } catch (Exception) { string path = Path.GetFullPath (inputFile); unit = new CompilationUnit (inputFile, path, 0); } CSharpParser parser = new CSharpParser (reader, unit, ctx); parser.Lexer.TabSize = 1; parser.Lexer.sbag = new SpecialsBag (); parser.LocationsBag = new LocationsBag (); parser.UsingsBag = new UsingsBag (); parser.parse (); return new CompilerCompilationUnit () { ModuleCompiled = RootContext.ToplevelTypes, LocationsBag = parser.LocationsBag, UsingsBag = parser.UsingsBag, SpecialsBag = parser.Lexer.sbag }; } finally { Reset (); } } }
public void Parse(SeekableStreamReader reader, CompilationUnit file, ModuleContainer module) { CSharpParser parser = new CSharpParser (reader, file, module); parser.parse (); }
public static CompilerCompilationUnit ParseFile (string[] args, Stream input, string inputFile, ReportPrinter reportPrinter) { lock (parseLock) { try { // Driver d = Driver.Create (args, false, null, reportPrinter); // if (d == null) // return null; var r = new Report (reportPrinter); CommandLineParser cmd = new CommandLineParser (r, Console.Out); var setting = cmd.ParseArguments (args); if (setting == null || r.Errors > 0) return null; CompilerContext ctx = new CompilerContext (setting, r); var files = new List<CompilationSourceFile> (); var unit = new CompilationSourceFile (inputFile, inputFile, 0); var module = new ModuleContainer (ctx); unit.NamespaceContainer = new NamespaceContainer (null, module, null, unit); files.Add (unit); Location.Initialize (files); // TODO: encoding from driver SeekableStreamReader reader = new SeekableStreamReader (input, Encoding.Default); RootContext.ToplevelTypes = module; CSharpParser parser = new CSharpParser (reader, unit); parser.Lexer.TabSize = 1; parser.Lexer.sbag = new SpecialsBag (); parser.LocationsBag = new LocationsBag (); parser.UsingsBag = new UsingsBag (); parser.parse (); return new CompilerCompilationUnit () { ModuleCompiled = RootContext.ToplevelTypes, LocationsBag = parser.LocationsBag, UsingsBag = parser.UsingsBag, SpecialsBag = parser.Lexer.sbag, LastYYValue = parser.LastYYVal }; } finally { Reset (); } } }
void Parse (SeekableStreamReader reader, CompilationUnit file) { CSharpParser parser = new CSharpParser (reader, file, ctx); parser.parse (); }
public static CompilerCompilationUnit ParseFile (string[] args, Stream input, string inputFile, ReportPrinter reportPrinter) { lock (parseLock) { try { // Driver d = Driver.Create (args, false, null, reportPrinter); // if (d == null) // return null; var r = new Report (reportPrinter); CommandLineParser cmd = new CommandLineParser (r, Console.Out); var setting = cmd.ParseArguments (args); if (setting == null || r.Errors > 0) return null; CompilerContext ctx = new CompilerContext (setting, r); var d = new Driver (ctx); Location.AddFile (null, inputFile); Location.Initialize (); // TODO: encoding from driver SeekableStreamReader reader = new SeekableStreamReader (input, Encoding.Default); RootContext.ToplevelTypes = new ModuleContainer (ctx); CompilationUnit unit = null; try { unit = (CompilationUnit) Location.SourceFiles [0]; } catch (Exception) { string path = Path.GetFullPath (inputFile); unit = new CompilationUnit (inputFile, path, 0); } CSharpParser parser = new CSharpParser (reader, unit, RootContext.ToplevelTypes); parser.Lexer.TabSize = 1; parser.Lexer.sbag = new SpecialsBag (); parser.LocationsBag = new LocationsBag (); parser.UsingsBag = new UsingsBag (); parser.parse (); return new CompilerCompilationUnit () { ModuleCompiled = RootContext.ToplevelTypes, LocationsBag = parser.LocationsBag, UsingsBag = parser.UsingsBag, SpecialsBag = parser.Lexer.sbag }; } finally { Reset (); } } }
public void Parse (SeekableStreamReader reader, CompilationSourceFile file, ModuleContainer module) { file.NamespaceContainer = new NamespaceContainer (null, module, null, file); CSharpParser parser = new CSharpParser (reader, file); parser.parse (); }
void Parse (SeekableStreamReader reader, CompilationUnit file) { CSharpParser parser = new CSharpParser (reader, file); parser.ErrorOutput = Report.Stderr; try { parser.parse (); } catch (Exception ex) { Report.Error(589, parser.Lexer.Location, "Compilation aborted in file `{0}', {1}", file.Name, ex); } }
public static CSharpParser Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report, int lineModifier = 0, int colModifier = 0) { var file = new CompilationSourceFile (module, sourceFile); module.AddTypeContainer(file); CSharpParser parser = new CSharpParser (reader, file, report, session); parser.Lexer.Line += lineModifier; parser.Lexer.Column += colModifier; parser.Lexer.sbag = new SpecialsBag (); parser.parse (); return parser; }
/// <summary> /// Parses the code and generate the compiled units. /// </summary> /// <param name="_code">The source code that is being parsed.</param> /// <returns>Zero if success, otherwise a non-zero value would return.</returns> /// <remarks> /// For more information about compiled units, please refer to <see cref="System.CodeDom.CodeCompileUnit"/>. /// </remarks> /// <seealso cref="System.CodeDom.CodeCompileUnit"/> public int Parse(string _code) { MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(_code)); CSharpParser parser = new CSharpParser(null, memoryStream, null); int ret = parser.parse(); codeCompileUnit__ = parser.Builder.CurrCompileUnit; return ret; }
public CSharpParser Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module) { var file = new CompilationSourceFile (module, sourceFile); module.AddTypeContainer (file); CSharpParser parser = new CSharpParser (reader, file); parser.Lexer.sbag = new SpecialsBag (); parser.parse (); return parser; }
public static void Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report) { var file = new CompilationSourceFile (module, sourceFile); module.AddTypeContainer (file); if (sourceFile.FileType == SourceFileType.CSharp) { CSharpParser parser = new CSharpParser (reader, file, session); parser.parse (); } else { PlayScriptParser parser = new PlayScriptParser (reader, file, session); parser.parsing_playscript = sourceFile.PsExtended; parser.parse (); } }