public void TestGetNamespaceContentsCase2 () { CompilationUnit unit = new CompilationUnit ("file.cs"); unit.Add (new DomType ("ANamespace.AnotherNamespace.AClass")); unit.Add (new DomType ("ANamespace.AnotherNamespace.BClass")); unit.Add (new DomType ("ANamespace.AnotherNamespace.CClass")); unit.Add (new DomType ("ANamespace.AClass2")); unit.Add (new DomType ("ANamespace.BClass2")); unit.Add (new DomType ("CClass3")); List<IMember> member = new List<IMember> (); unit.GetNamespaceContents (member, "ANamespace", true); Assert.AreEqual (3, member.Count); Namespace ns = member[0] as Namespace; Assert.IsNotNull (ns); Assert.AreEqual ("AnotherNamespace", ns.Name); IType type = member[1] as IType; Assert.IsNotNull (type); Assert.AreEqual ("AClass2", type.Name); type = member[2] as IType; Assert.IsNotNull (type); Assert.AreEqual ("BClass2", type.Name); }
public void ReplaceJumpToIf() { var cu = new CompilationUnit().AddStatements(new Statement[] { new JumpStatement( new BinaryExpression( new SimpleName("Var1"), Operator.Greater, 0.ToLiteral()), 10){ StartOffset = 0, EndOffset = 5 }, new ExpressionStatement( new MethodInvocation("Print").AddArgument("Var1 is lower or equals to 0".ToLiteral())) { StartOffset = 5, EndOffset = 10 }, new ExpressionStatement( new MethodInvocation("Print").AddArgument("End".ToLiteral())) { StartOffset = 10, EndOffset = 15 } }); var expectedCu = new CompilationUnit().AddStatements(new Statement[] { new IfStatement( new BinaryExpression( new SimpleName("Var1"), Operator.LowerOrEquals, 0.ToLiteral()), new BlockStatement().AddStatement( new ExpressionStatement( new MethodInvocation("Print").AddArgument("Var1 is lower or equals to 0".ToLiteral())) { StartOffset = 5, EndOffset = 10 }) ){ StartOffset = 0, EndOffset = 10 }, new ExpressionStatement( new MethodInvocation("Print").AddArgument("End".ToLiteral())) { StartOffset = 10, EndOffset = 15 } }); var actualCu = new ReplaceJumpToIf().Replace(cu); AstHelper.AstEquals(expectedCu, actualCu); }
public ToolTipData (ICSharpCode.NRefactory.CSharp.CompilationUnit unit, ICSharpCode.NRefactory.Semantics.ResolveResult result, ICSharpCode.NRefactory.CSharp.AstNode node, CSharpAstResolver file) { this.Unit = unit; this.Result = result; this.Node = node; this.Resolver = file; }
void Init(string code) { compilationUnit = new CSharpParser().Parse(new StringReader(code), "test.cs"); parsedFile = compilationUnit.ToTypeSystem(); compilation = TypeSystemHelper.CreateCompilation(parsedFile); findReferences = new FindReferences(); }
private string Translate(CompilationUnit typedCompilationUnit) { var code = new CodeWriter(); WriteAction write = typedCompilationUnit.Visit(csTranslator); write(code); return code.ToString(); }
public PsiVisitor(CompilationUnit cu, CompilerDTO dto) { DTO = dto; CurrentCompilationUnit = cu; InitHelpers(); }
public void ReplaceJumpToWhile() { var cu = new CompilationUnit().AddStatements(new Statement[] { new ExpressionStatement(new MethodInvocation("Delay").AddArgument(60)){ StartOffset = 0, EndOffset = 4 }, new ExpressionStatement(new BinaryExpression(new ElementAccess("LocalVariables", 0), Operator.Assignment, new MethodInvocation("GetRandomNumber").AddArgument(10))){ StartOffset = 4, EndOffset = 8 }, new ExpressionStatement(new BinaryExpression(new ElementAccess("Variables", 103), Operator.Assignment, 0.ToLiteral())){ StartOffset = 8, EndOffset = 13 }, new JumpStatement(true.ToLiteral(), 0){ StartOffset = 13, EndOffset = 16 }, new ExpressionStatement(new MethodInvocation("StopObjectCode")){ StartOffset = 16, EndOffset = 17 }, }); var expectedCu = new CompilationUnit().AddStatements(new Statement[] { new DoWhileStatement(true.ToLiteral(), new BlockStatement().AddStatements( new Statement[] { new ExpressionStatement(new MethodInvocation("Delay").AddArgument(60)){ StartOffset = 0, EndOffset = 4 }, new ExpressionStatement(new BinaryExpression(new ElementAccess("LocalVariables", 0), Operator.Assignment, new MethodInvocation("GetRandomNumber").AddArgument(10))){ StartOffset = 4, EndOffset = 8 }, new ExpressionStatement(new BinaryExpression(new ElementAccess("Variables", 103), Operator.Assignment, 0.ToLiteral())){ StartOffset = 8, EndOffset = 13 }, })), new ExpressionStatement(new MethodInvocation("StopObjectCode")){ StartOffset = 16, EndOffset = 17 }, }); var actualCu = new ReplaceJumpToWhile().Replace(cu); AstHelper.AstEquals(expectedCu, actualCu); }
public GatherVisitor (BaseRefactoringContext context, CompilationUnit unit, AccessToClosureIssue issueProvider) : base (context) { this.title = context.TranslateString (issueProvider.Title); this.unit = unit; this.issueProvider = issueProvider; }
public void Validate(CompilationUnit cu) { foreach (AstNode node in cu.DescendantsAndSelf.Except(resolvedNodes)) { if (!CSharpAstResolver.IsUnresolvableNode(node)) { Console.WriteLine("Forgot to resolve " + node); } } }
public PsiSemanticAnaliserVisitor(CompilationUnit cu, CompilerDTO dto) : base(cu, dto) { CurrentCompilationUnit = cu; DTO = dto; InitHelpers(); }
public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data) { base.VisitCompilationUnit(compilationUnit, data); for (int i = 0; i < nodesToMoveToCompilationUnit.Count; i++) { compilationUnit.Children.Insert(i, nodesToMoveToCompilationUnit[i]); nodesToMoveToCompilationUnit[i].Parent = compilationUnit; } return null; }
public CSharpParameterCompletionEngine (IDocument document, IParameterCompletionDataFactory factory, IProjectContent content, CSharpTypeResolveContext ctx, CompilationUnit unit, CSharpParsedFile parsedFile) : base (content, ctx, unit, parsedFile) { if (document == null) throw new ArgumentNullException ("document"); if (factory == null) throw new ArgumentNullException ("factory"); this.document = document; this.factory = factory; }
public CompilationUnit Replace(CompilationUnit cu) { var visitor = new JumpAstVisitor(); cu.Accept(visitor); var jumps = visitor.Jumps.Where(AcceptJump).ToList(); var newCu = cu.Accept(new JumpReplacer()); newCu.Accept(new LabelInserter(jumps)); return (CompilationUnit)newCu; }
public DynamicallyCompiledLibraries(ErrorCollector collector) { this.collector = collector; var name = "DynamicallyCompiledLibraries" + GetHashCode(); var assembly_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run); CompilationUnit.MakeDebuggable(assembly_builder); var module_builder = assembly_builder.DefineDynamicModule(name, true); unit = new CompilationUnit(module_builder, true); }
public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, out AstNode node, CancellationToken cancellationToken = default(CancellationToken)) { node = cu.GetNodeAt(location); if (node == null || node is ArrayInitializerExpression) return null; if (CSharpAstResolver.IsUnresolvableNode(node)) { if (node is Identifier) { node = node.Parent; } else if (node.NodeType == NodeType.Token) { if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer) { Console.WriteLine (2); // There's no other place where one could hover to see the indexer's tooltip, // so we need to resolve it when hovering over the '[' or ']'. // For constructor initializer, the same applies to the 'base'/'this' token. node = node.Parent; } else { return null; } } else { // don't resolve arbitrary nodes - we don't want to show tooltips for everything return null; } } else { // It's a resolvable node. // However, we usually don't want to show the tooltip everywhere // For example, hovering with the mouse over an empty line between two methods causes // node==TypeDeclaration, but we don't want to show any tooltip. if (!node.GetChildByRole(Roles.Identifier).IsNull) { // We'll suppress the tooltip for resolvable nodes if there is an identifier that // could be hovered over instead: return null; } } if (node == null) return null; if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) { node = node.Parent; } InvocationExpression parentInvocation = null; if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) { // we also need to resolve the invocation parentInvocation = node.Parent as InvocationExpression; } // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, cu, parsedFile); ResolveResult rr = resolver.Resolve(node, cancellationToken); if (rr is MethodGroupResolveResult && parentInvocation != null) return resolver.Resolve(parentInvocation); else return rr; }
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, CancellationToken cancellationToken = default(CancellationToken)) { AstNode node = cu.GetNodeAt(location); if (node == null) return null; AstNode resolvableNode; if (node is AstType) { resolvableNode = node; if (resolvableNode.Parent is ComposedType) { while (resolvableNode.Parent is ComposedType) resolvableNode = resolvableNode.Parent; //node is preffered over the resolvable node. Which shouldn't be done in the case of nullables, arrays etc. node = resolvableNode; } } else if (node is Identifier) { resolvableNode = node.Parent; } else if (node.NodeType == NodeType.Token) { if (node.Parent is ConstructorInitializer) { resolvableNode = node.Parent; } else { return null; } } else { // don't resolve arbitrary nodes - we don't want to show tooltips for everything return null; } if (resolvableNode != null && resolvableNode.Parent is ObjectCreateExpression) { resolvableNode = resolvableNode.Parent; } InvocationExpression parentInvocation = null; if ((resolvableNode is IdentifierExpression || resolvableNode is MemberReferenceExpression || resolvableNode is PointerReferenceExpression)) { // we also need to resolve the invocation parentInvocation = resolvableNode.Parent as InvocationExpression; } IResolveVisitorNavigator navigator; if (parentInvocation != null) navigator = new NodeListResolveVisitorNavigator(new[] { resolvableNode, parentInvocation }); else navigator = new NodeListResolveVisitorNavigator(new[] { resolvableNode }); CSharpResolver resolver = new CSharpResolver(compilation); ResolveVisitor v = new ResolveVisitor(resolver, parsedFile, navigator); v.Scan(cu); // Prefer the RR from the token itself, if it was assigned a ResolveResult // (this can happen with the identifiers in various nodes such as catch clauses or foreach statements) ResolveResult rr = v.GetResolveResult(node) ?? v.GetResolveResult(resolvableNode); if (rr is MethodGroupResolveResult && parentInvocation != null) return v.GetResolveResult(parentInvocation); else return rr; }
protected static bool FindUsage (BaseRefactoringContext context, CompilationUnit unit, ITypeParameter typaParameter, AstNode declaration) { var found = false; refFinder.FindTypeParameterReferences (typaParameter, context.ParsedFile, unit, context.Compilation, (node, resolveResult) => { found = found || node != declaration; }, context.CancellationToken); return found; }
void CSharpParseButtonClick(object sender, EventArgs e) { CSharpParser parser = new CSharpParser(); compilationUnit = parser.Parse(new StringReader(csharpCodeTextBox.Text)); csharpTreeView.Nodes.Clear(); foreach (var element in compilationUnit.Children) { csharpTreeView.Nodes.Add(MakeTreeNode(element)); } SelectCurrentNode(csharpTreeView.Nodes); resolveButton.Enabled = true; }
/// <summary> /// Creates a new C# AST resolver. /// Use this overload if you are resolving within a complete C# file. /// </summary> /// <param name="compilation">The current compilation.</param> /// <param name="compilationUnit">The compilation unit corresponding to the specified parsed file.</param> /// <param name="parsedFile"> /// Optional: Result of the <see cref="TypeSystemConvertVisitor"/> for the file being resolved. /// <para> /// This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// </para> /// <para> /// When a parsedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify /// member declarations in the AST with members in the type system. /// When no parsedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the /// member's signature in the AST with the signature in the type system. /// </para> /// </param> public CSharpAstResolver(ICompilation compilation, CompilationUnit compilationUnit, CSharpParsedFile parsedFile = null) { if (compilation == null) throw new ArgumentNullException("compilation"); if (compilationUnit == null) throw new ArgumentNullException("compilationUnit"); this.initialResolverState = new CSharpResolver(compilation); this.rootNode = compilationUnit; this.parsedFile = parsedFile; this.resolveVisitor = new ResolveVisitor(initialResolverState, parsedFile); }
public CompilerResult Build(CompilationUnit compilationUnit) { var typeChecker = new TypeChecker(); var typedCompilationUnit = typeChecker.TypeCheck(compilationUnit); if (typeChecker.HasErrors) return new CompilerResult(Language.Rook, typeChecker.Errors); string translatedCode = Translate(typedCompilationUnit); return csCompiler.Build(translatedCode); }
public void InitializeTest() { _compilationUnit = new CompilationUnit(); _compilation = new Compilation(new SourceAssembly("TestAssembly") { SourceFiles = { new SourceFile("dummy") { CompilationUnit = _compilationUnit } } }) { Assemblies = { _mscorlibAssembly }, }; }
public CompilationUnit Replace(CompilationUnit cu) { var visitor = new JumpAstVisitor(); cu.Accept(visitor); var jumps = visitor.Jumps.Where(jump => jump.JumpOffset < jump.StartOffset).OrderByDescending(jmp => jmp.JumpOffset).ThenByDescending(jmp => jmp.StartOffset).ToList(); foreach (var jump in jumps) { cu = new CompilationUnit().AddStatements(ReplaceJump(jump, cu.Statement)); } return cu; }
public static void OptimizeCompilationUnit(CompilationUnit tree) { tree.AcceptVisitor(new InlineTemporaryCVariablesVisitor()); var visitors = GetVisitors(); string oldText = null; while (tree.GetText() != oldText) { oldText = tree.GetText(); foreach (var visitor in visitors) tree.AcceptVisitor(visitor); } }
private CompilerResult Build(CompilationUnit compilationUnit, out string translation) { translation = ""; var typeChecker = new TypeChecker(); var typedCompilationUnit = typeChecker.TypeCheck(compilationUnit); if (typeChecker.HasErrors) return new CompilerResult(Language.Rook, typeChecker.Errors); translation = Translate(typedCompilationUnit); return csCompiler.Build(translation); }
public CppCompletionEngine (IDocument document, ICompletionDataFactory factory, IProjectContent content, CppTypeResolveContext ctx, CompilationUnit unit, CppParsedFile parsedFile) : base (content, ctx, unit, parsedFile) { if (document == null) throw new ArgumentNullException ("document"); if (factory == null) throw new ArgumentNullException ("factory"); this.document = document; this.factory = factory; // Set defaults for additional input properties this.FormattingPolicy = new CppFormattingOptions(); this.EolMarker = Environment.NewLine; this.IndentString = "\t"; }
public CompilationUnit TypeCheck(CompilationUnit compilationUnit) { var position = compilationUnit.Position; var classes = compilationUnit.Classes; var functions = compilationUnit.Functions; foreach (var @class in classes)//TODO: Test coverage. typeRegistry.Add(@class); var scope = CreateGlobalScope(classes, functions); return new CompilationUnit(position, TypeCheck(classes, scope), TypeCheck(functions, scope)); }
public static int Main(string[] args) { var trace = false; var show_help = false; var options = new OptionSet { {"t|trace-parsing", "Produce a trace of the parse process.", v => trace = v != null}, {"h|help", "show this message and exit", v => show_help = v != null} }; List<string> files; try { files = options.Parse(args); } catch (OptionException e) { Console.Write(AppDomain.CurrentDomain.FriendlyName + ": "); Console.WriteLine(e.Message); Console.WriteLine("Try “" + AppDomain.CurrentDomain.FriendlyName + " --help” for more information."); return 1; } if (show_help) { Console.WriteLine("Usage: " + AppDomain.CurrentDomain.FriendlyName + " files ..."); Console.WriteLine("Compile a Flabbergast file to native CLR."); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); return 0; } if (files.Count == 0) { Console.WriteLine("Perhaps you wish to compile some source files?"); return 1; } var collector = new ConsoleCollector(); foreach (var filename in files) { var parser = Parser.Open(filename); parser.Trace = trace; var dll_name = Path.ChangeExtension(Path.GetFileNameWithoutExtension(filename), ".dll"); var type_name = Regex.Replace("Flabbergast.Library." + Path.GetDirectoryName(filename).Replace(Path.DirectorySeparatorChar, '.') + Path.GetFileNameWithoutExtension(filename), "\\.+", "."); var assembly_name = new AssemblyName(type_name) {CodeBase = "file://" + Path.GetDirectoryName(filename)}; var assembly_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(assembly_name, AssemblyBuilderAccess.RunAndSave); CompilationUnit.MakeDebuggable(assembly_builder); var module_builder = assembly_builder.DefineDynamicModule(type_name, dll_name, true); var unit = new CompilationUnit(module_builder, true); var type = parser.ParseFile(collector, unit, type_name); if (type != null) { assembly_builder.Save(dll_name); } } return 0; }
protected CppCompletionEngineBase (IProjectContent content, CppTypeResolveContext ctx, CompilationUnit unit, CppParsedFile parsedFile) { if (content == null) throw new ArgumentNullException ("content"); if (ctx == null) throw new ArgumentNullException ("ctx"); if (unit == null) throw new ArgumentNullException ("unit"); if (parsedFile == null) throw new ArgumentNullException ("parsedFile"); this.ProjectContent = content; this.ctx = ctx; this.Unit = unit; this.CSharpParsedFile = parsedFile; }
public void ReplaceLocalVariables() { var cu = new CompilationUnit().AddStatements(new [] { new BinaryExpression( new ElementAccess("Variables", 0x40000000), Operator.Assignment, new ElementAccess("Variables", 0x40000001)).ToStatement() }); var expectedCu = new CompilationUnit().AddStatements(new [] { new BinaryExpression( new ElementAccess("Locals", 0), Operator.Assignment, new ElementAccess("Locals", 1)).ToStatement() }); var resolver = new ResolveAllTypesOfVariables(8); var actualCu = resolver.Replace(cu); AstHelper.AstEquals(expectedCu, actualCu); }
public void ReplacePushAndPopWithUnary() { var cu = new CompilationUnit().AddStatements(new Statement[] { new MethodInvocation("Push").AddArgument(0.ToLiteral()).ToStatement(), new MethodInvocation("Push").AddArgument(false.ToLiteral()).ToStatement(), new JumpStatement(new UnaryExpression(new MethodInvocation("Pop"), Operator.Not), 0) }); var expectedCu = new CompilationUnit().AddStatements(new Statement[] { new JumpStatement(new UnaryExpression(false.ToLiteral(), Operator.Not), 0) }); var actualCu = new ReplacePushAndPop().Replace(cu); AstHelper.AstEquals(expectedCu, actualCu); }
public void InheritedMethodUsingInnerClass() { string program = TestUtil.GetInput(); string expected = TestUtil.GetExpected(); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration ty1 = (TypeDeclaration)ns.Children[0]; TypeDeclaration ty2 = (TypeDeclaration)ty1.Children[0]; TypeDeclaration ty3 = (TypeDeclaration)ns.Children[1]; CodeBase.Types.Add("Test.A", ty1); CodeBase.Types.Add("Test.A.Ab", ty2); CodeBase.Types.Add("Test.B", ty3); VisitCompilationUnit(cu, null); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
private TypeMappingCollection BuildTypeMappings(CompilationUnit compilationUnit) { var mappings = new TypeMappingCollection(); mappings.RegisterTypeMapping("Label", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.Label"), false)); mappings.RegisterTypeMapping("CommandButton", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.Button"), false)); mappings.RegisterTypeMapping("Frame", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.GroupBox"), true)); mappings.RegisterTypeMapping("ComboBox", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.ComboBox"), false)); mappings.RegisterTypeMapping("HScrollBar", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.HScrollBar"), false)); mappings.RegisterTypeMapping("VScrollBar", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.VScrollBar"), false)); mappings.RegisterTypeMapping("TextBox", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.TextBox"), false)); mappings.RegisterTypeMapping("PictureBox", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.PictureBox"), false)); mappings.RegisterTypeMapping("ListBox", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.ListBox"), false)); mappings.RegisterTypeMapping("CheckBox", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.CheckBox"), false)); mappings.RegisterTypeMapping("OptionButton", () => new TypeMapping(compilationUnit.Generator.IdentifierName("System.Windows.Forms.RadioButton"), false)); return(mappings); }
private TypeBuilderSkeletonStep CreateAssemblyStructure(CompilationUnit unit) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "RookGenAssembly"; AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Save); ModuleBuilder module = assembly.DefineDynamicModule( "RookModule", "RookModule.mod", true); unit.AssemblyBuilder = assembly; unit.ModuleBuilder = module; return(new TypeBuilderSkeletonStep(module, typeContainer, resolver, errorReport)); }
public void ReplacePushAndPopWithDup() { var cu = new CompilationUnit().AddStatements(new Statement[] { new MethodInvocation("Dup").AddArgument(false.ToLiteral()).ToStatement(), new JumpStatement(new UnaryExpression(new MethodInvocation("Pop"), Operator.Not), 0), new MethodInvocation("Print").AddArguments(new MethodInvocation("Pop")).ToStatement() }); var expectedCu = new CompilationUnit().AddStatements(new Statement[] { new JumpStatement(new UnaryExpression(false.ToLiteral(), Operator.Not), 0), new MethodInvocation("Print").AddArgument(false).ToStatement(), }); var actualCu = new ReplacePushAndPop().Replace(cu); AstHelper.AstEquals(expectedCu, actualCu); }
public void loadCompilationUnit(string filePath, List <ISpecial> specials, CompilationUnit compilationUnit) { //store specials FileToSpecials.add(filePath, specials); // map all INodes FileToINodes.add(filePath, new GetAllINodes(compilationUnit)); FileToCompilationUnit.add(filePath, compilationUnit); //Map AsT to DOM (System.DOM classes) MapAstToDom.loadCompilationUnit(compilationUnit); //Map AST to NRefactory (ICompilationUnit, IClass, IMethod) MapAstToNRefactory.loadCompilationUnit(compilationUnit); // update variable for CodeComplete O2AstResolver.setCurrentCompilationUnit(compilationUnit); var iCompilationUnit = MapAstToNRefactory.CompilationUnitToICompilationUnit[compilationUnit]; O2AstResolver.myProjectContent.UpdateCompilationUnit(null, iCompilationUnit, ""); }
/// <summary> /// Creates a new C# AST resolver. /// </summary> /// <param name="compilation">The current compilation.</param> /// <param name="parsedFile"> /// Result of the <see cref="TypeSystemConvertVisitor"/> for the file being passed. This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// </param> /// <param name="compilationUnit">The compilation unit corresponding to the specified parsed file.</param> public CSharpAstResolver(ICompilation compilation, CompilationUnit compilationUnit, CSharpParsedFile parsedFile) { if (compilation == null) { throw new ArgumentNullException("compilation"); } if (parsedFile == null) { throw new ArgumentNullException("parsedFile"); } if (compilationUnit == null) { throw new ArgumentNullException("compilationUnit"); } this.initialResolverState = new CSharpResolver(compilation); this.rootNode = compilationUnit; this.parsedFile = parsedFile; }
public CSharpAstResolver CreateResolver(CompilationUnit unit) { var parsedDocument = Document.ParsedDocument; if (parsedDocument == null) { return(null); } var parsedFile = parsedDocument.ParsedFile as CSharpParsedFile; if (unit == null || parsedFile == null) { return(null); } return(new CSharpAstResolver(Document.Compilation, unit, parsedFile)); }
public static void InsertSpecials(CompilationUnit unit, IList <ISpecial> specials) { IOutputAstVisitor outputVisitor = new CSharpOutputVisitor(); using (SpecialNodesUserDataInserter.Install(specials, outputVisitor)) { unit.AcceptVisitor(outputVisitor, null); } /* * List<ISpecial> collectedSpecials = new List<ISpecial>(); * CollectSpecials(collectedSpecials, unit.Children); * * if (collectedSpecials.Count != specials.Count) { * Console.Out.WriteLine(collectedSpecials.Count); * Console.Out.WriteLine(specials.Count); * * }*/ }
public void HierarchyOverriding() { string program = TestUtil.GetInput(); string expected = TestUtil.GetExpected(); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration tyC = (TypeDeclaration)ns.Children[0]; TypeDeclaration tyB = (TypeDeclaration)ns.Children[1]; TypeDeclaration tyA = (TypeDeclaration)ns.Children[2]; CodeBase.Types.Add("Test.A", tyA); CodeBase.Types.Add("Test.B", tyB); CodeBase.Types.Add("Test.C", tyC); VisitCompilationUnit(cu, null); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
public void OverrideMethodWithPartialFullType() { string program = TestUtil.GetInput(); string expected = TestUtil.GetExpected(); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration ty1 = (TypeDeclaration)ns.Children[0]; TypeDeclaration ty2 = (TypeDeclaration)ns.Children[1]; TypeDeclaration ty3 = (TypeDeclaration)ty2.Children[0]; CodeBase.Types.Add("Test.Test", ty1); CodeBase.Types.Add("Test.A", ty2); CodeBase.Types.Add("Test.A.B", ty3); VisitCompilationUnit(cu, null); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
public void PropertyRegionTest() { const string code = "class T {\n\tint Prop {\n\t\tget { return f; }\n\t\tset { f = value; }\n\t}\n}\n"; int line2Pos = code.IndexOf("\tint Prop"); int line3Pos = code.IndexOf("\t\tget"); int line4Pos = code.IndexOf("\t\tset"); CSharpParser parser = new CSharpParser(); CompilationUnit cu = parser.Parse(new StringReader(code)); PropertyDeclaration pd = (PropertyDeclaration)cu.Children.Single().GetChildByRole(TypeDeclaration.MemberRole); Assert.AreEqual(new TextLocation(2, code.IndexOf("{\n\t\tget") - line2Pos + 1), pd.GetChildByRole(AstNode.Roles.LBrace).StartLocation); Assert.AreEqual(new TextLocation(5, 3), pd.EndLocation); Assert.AreEqual(new TextLocation(3, code.IndexOf("{ return") - line3Pos + 1), pd.Getter.Body.StartLocation); Assert.AreEqual(new TextLocation(3, code.IndexOf("}\n\t\tset") + 1 - line3Pos + 1), pd.Getter.Body.EndLocation); Assert.AreEqual(new TextLocation(4, code.IndexOf("{ f =") - line4Pos + 1), pd.Setter.Body.StartLocation); Assert.AreEqual(new TextLocation(4, code.IndexOf("}\n\t}") + 1 - line4Pos + 1), pd.Setter.Body.EndLocation); }
internal static void Check(string testName, bool debug = false) { // Compile test file CompilationUnit compilationUnit = ParserUtils.ParseCobolFile(testName, null); // Check code elements string result = ParserUtils.DumpCodeElements(compilationUnit.CodeElementsDocumentSnapshot); if (debug) { //Console.WriteLine(compilationUnit.CodeElementsDocumentSnapshot.CodeElements.Count+" CodeElements found:"); foreach (var e in compilationUnit.CodeElementsDocumentSnapshot.CodeElements) { Console.WriteLine("> " + e); } Console.WriteLine("result:\n" + result); } ParserUtils.CheckWithResultFile(result, testName); }
public void MultiLevel() { string program = TestUtil.GetInput(); string expected = TestUtil.GetExpected(); CompilationUnit cu = TestUtil.ParseProgram(program); TypeDeclaration type1 = ((NamespaceDeclaration)cu.Children[0]).Children[0] as TypeDeclaration; TypeDeclaration type2 = ((NamespaceDeclaration)cu.Children[0]).Children[1] as TypeDeclaration; TypeDeclaration type3 = ((NamespaceDeclaration)cu.Children[0]).Children[2] as TypeDeclaration; CodeBase.Types.Add("Test.A", type1); CodeBase.Types.Add("Test.B", type2); CodeBase.Types.Add("Test.IC", type3); VisitCompilationUnit(cu, null); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
public void Cast() { string program = @"package Test public class A { public void Method() { B b; a = ((StmExpression)b.Expr).Count; } } public class B { public Expression Expr; } public class Expression {} public class StmExpression extends Expression { public int Count; }" ; CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration ty0 = (TypeDeclaration)ns.Children[0]; TypeDeclaration ty1 = (TypeDeclaration)ns.Children[1]; TypeDeclaration ty2 = (TypeDeclaration)ns.Children[2]; TypeDeclaration ty3 = (TypeDeclaration)ns.Children[3]; CodeBase.Types.Clear(); CodeBase.Types.Add("Test.A", ty0); CodeBase.Types.Add("Test.B", ty1); CodeBase.Types.Add("Test.Expression", ty2); CodeBase.Types.Add("Test.StmExpression", ty3); MethodDeclaration md = (MethodDeclaration)ty0.Children[0]; ExpressionStatement se = (ExpressionStatement)md.Body.Children[1]; AssignmentExpression assignmentExpression = (AssignmentExpression)se.Expression; FieldReferenceExpression fr = (FieldReferenceExpression)assignmentExpression.Right; TypeReference ivType = GetType(fr); Assert.IsNotNull(ivType); Assert.AreEqual("int", ivType.Type); }
public void CSharpCodeGenerator_Factorial() { var unit = new CompilationUnit(); var ns = unit.AddNamespace("Meziantou.Framework.CodeDom"); var c = ns.AddType(new ClassDeclaration("Sample")); var method = c.AddMember(new MethodDeclaration("Factorial")); method.ReturnType = typeof(int); var n = method.AddArgument("n", typeof(int)); method.Modifiers = Modifiers.Public | Modifiers.Static; method.Statements = new ConditionStatement() { Condition = new BinaryExpression(BinaryOperator.LessThanOrEqual, 1, n), TrueStatements = new ReturnStatement(1), FalseStatements = new ReturnStatement(new BinaryExpression( BinaryOperator.Multiply, n, new MethodInvokeExpression(method, new BinaryExpression(BinaryOperator.Substract, n, 1)))) }; var generator = new CSharpCodeGenerator(); var result = generator.Write(unit); Assert.That.StringEquals(@"namespace Meziantou.Framework.CodeDom { class Sample { public static int Factorial(int n) { if ((1 <= n)) { return 1; } else { return (n * this.Factorial((n - 1))); } } } } ", result); }
public SourceUnit(String content) { using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content))) { parser.Parse(); if (parser.Errors.Count > 0) { throw new Exception(parser.Errors.ErrorOutput); } specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); unit = parser.CompilationUnit; NRefactoryUtil.InsertSpecials(unit, specials); //List<ISpecial> rightSpecials = new List<ISpecial>(); //rightSpecials.AddRange(specials); //MapSpecials(unit.Children, rightSpecials); // //if (rightSpecials.Count > 0) { // System.Diagnostics.Debug.WriteLine("There are specials that did not get mapped to members."); //} } foreach (INode child in unit.Children) { if (child is UsingDeclaration) { imports.Add(child as UsingDeclaration); } else if (child is NamespaceDeclaration) { namespaces.Add(new NamespaceUnit(child as NamespaceDeclaration)); } else if (child is TypeDeclaration) { if (namespaces.Count == 0) { namespaces.Add(new NamespaceUnit()); } namespaces[0].AddType(new TypeUnit(child as TypeDeclaration)); } else { throw new Exception("Unknown node type: " + child.GetType() + " - " + child.ToString()); } } }
public void Generate(CompilationUnit compilationUnit, ColumnsLayout columns = ColumnsLayout.FreeTextFormat) { Destination.Append(""); //Add version to output file if (!string.IsNullOrEmpty(TypeCobolVersion)) { Destination.AppendLine(" *TypeCobol_Version:" + TypeCobolVersion); } var sourceFile = compilationUnit.ProgramClassDocumentSnapshot.Root; sourceFile.AcceptASTVisitor(new ExportToDependency()); var lines = sourceFile.SelfAndChildrenLines; foreach (var textLine in lines) { Destination.AppendLine(textLine.Text); } }
/// <summary> /// Returns completions for namespace aliases with the given prefix that are visible at the given position in /// the file. /// <para/> /// Note: a dot will be added after the given prefix if it is not the empty string, and doesn't already end with /// a dot. /// </summary> /// <exception cref="ArgumentNullException">Thrown when any argument is null.</exception> /// <exception cref="ArgumentException">Thrown when the position is invalid.</exception> private static IEnumerable <CompletionItem> GetNamespaceAliasCompletions( FileContentManager file, CompilationUnit compilation, Position position, string prefix = "") { if (file == null) { throw new ArgumentNullException(nameof(file)); } if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } if (!Utils.IsValidPosition(position)) { throw new ArgumentException(nameof(position)); } if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } if (prefix.Length != 0 && !prefix.EndsWith(".")) { prefix += "."; } var @namespace = file.TryGetNamespaceAt(position); if (@namespace == null || !compilation.GlobalSymbols.NamespaceExists(NonNullable <string> .New(@namespace))) { return(Array.Empty <CompletionItem>()); } return(compilation .GetOpenDirectives(NonNullable <string> .New(@namespace))[file.FileName] .Where(open => open.Item2 != null && open.Item2.StartsWith(prefix)) .GroupBy(open => NextNamespacePart(open.Item2, prefix.Length)) .Select(open => new CompletionItem() { Label = open.Key, Kind = CompletionItemKind.Module, Detail = open.Count() == 1 && prefix + open.Key == open.Single().Item2 ? open.Single().Item1.Value : prefix + open.Key })); }
/// <summary> /// Returns documentation for the callable (if kind is Function or Constructor) or type (if kind is Struct) in /// the compilation unit with the given qualified name. Returns null if no documentation is available or the /// completion item data is missing properties. /// </summary> /// <exception cref="ArgumentNullException">Thrown when any argument is null.</exception> private static string TryGetDocumentation( CompilationUnit compilation, CompletionItemData data, CompletionItemKind kind, bool useMarkdown) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.QualifiedName == null || data.SourceFile == null || !compilation.GlobalSymbols.NamespaceExists(data.QualifiedName.Namespace)) { return(null); } switch (kind) { case CompletionItemKind.Function: case CompletionItemKind.Constructor: var callable = compilation.GlobalSymbols.TryGetCallable( data.QualifiedName, data.QualifiedName.Namespace, NonNullable <string> .New(data.SourceFile)); if (callable.IsNull) { return(null); } var signature = callable.Item.PrintSignature(); var documentation = callable.Item.Documentation.PrintSummary(useMarkdown); return(signature.Trim() + "\n\n" + documentation.Trim()); case CompletionItemKind.Struct: var type = compilation.GlobalSymbols.TryGetType( data.QualifiedName, data.QualifiedName.Namespace, NonNullable <string> .New(data.SourceFile)) .Item; return(type?.Documentation.PrintSummary(useMarkdown).Trim()); default: return(null); } }
/// <summary> /// parse a c# file /// </summary> /// <param name="fileName"></param> /// <returns></returns> public CompilationUnit ParseFile(string fileName) { // Console.WriteLine("\nParsing " + fileName); IParser parser = ParserFactory.CreateParser(fileName); parser.Parse(); CompilationUnit cu = parser.CompilationUnit; if (parser.Errors.Count > 0) { Console.WriteLine(); PrintErrors(fileName, parser.Errors); return(null); } return(cu); }
/// <summary> /// Returns completions for all global namespaces with the given prefix. The completion names contain only the /// word after the prefix and before the next dot. /// <para/> /// Note: a dot will be added after the given prefix if it is not the empty string, and doesn't already end with /// a dot. /// </summary> private static IEnumerable <CompletionItem> GetGlobalNamespaceCompletions( CompilationUnit compilation, string prefix = "") { if (prefix.Length != 0 && !prefix.EndsWith(".")) { prefix += "."; } return (compilation.GlobalSymbols.NamespaceNames() .Where(name => name.StartsWith(prefix)) .Select(name => NextNamespacePart(name, prefix.Length)) .Distinct() .Select(name => new CompletionItem() { Label = name, Kind = CompletionItemKind.Module, Detail = prefix + name })); }
public void Parse() { var unit = new CompilationUnit(); using (mocks.Unordered()) { Expect.Call(parserFactory.CreateCSharpParser(null)).Constraints(Is.NotNull()).Return(parser); parser.ParseMethodBodies = true; parser.Parse(); typeResolver.Clear(); Expect.Call(parser.CompilationUnit).Return(unit); Expect.Call(visitor.VisitCompilationUnit(unit, null)).Return(null); sources.Add(path, parser); } mocks.ReplayAll(); service.Parse(visitor, path); mocks.VerifyAll(); }
public void FormalArgumentsUsage() { String contents = "def some(x:int, y:int) \r\n" + " puts(x + y) \r\n" + "end \r\n" + ""; CompilationUnit unit = container.ParserService.Parse(contents); AssertNoErrorOrWarnings(); Assert.IsNotNull(unit); Assert.AreEqual(2, unit.Statements.Count); RunPasses(unit); AssertNoErrorOrWarnings(); }
public void MethodInDefaultType() { string program = TestUtil.StatementParse("getClass();"); string expected = TestUtil.CSharpStatementParse("java.lang.Object.instancehelper_getClass(this);"); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration type = (TypeDeclaration)ns.Children[0]; TypeReference objectType = new TypeReference("java.lang.Object"); type.BaseTypes.Add(objectType); CodeBase.Types.Clear(); CodeBase.Types.Add("Test.Test", type); VisitCompilationUnit(cu, null); RemoveBaseTypeFrom(type, objectType); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
public NotificationChain basicSetOriginalCompilationUnit(CompilationUnit newobj, NotificationChain msgs) { var oldobj = _originalCompilationUnit; _originalCompilationUnit = newobj; if (eNotificationRequired()) { var notification = new ENotificationImpl(this, NotificationImpl.SET, Java_PackageImpl.ASTNODE_ORIGINALCOMPILATIONUNIT, oldobj, newobj); if (msgs == null) { msgs = notification; } else { msgs.add(notification); } } return(msgs); }
public void MethodChain() { string program = TestUtil.PackageMemberParse(@" import java.util.Map; public class Test { public void Method() { Map map; obj = map.keySet().iterator(); } }" ); CompilationUnit cu = TestUtil.ParseProgram(program); VisitCompilationUnit(cu, null); string expected = TestUtil.NamespaceMemberParse(@" using java.util.Map; public class Test { public void Method() { Map map; obj = new System.Collections.ArrayList(map.Keys).GetEnumerator();} }" ); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }
public static void Main(string[] args) { Console.WriteLine("(C) 2011 acceptCsharp @ softlang in Koblenz"); if (args.Length < 1) { Console.WriteLine("Usage: acceptCsharp file.cs"); Environment.Exit(-1); } var parser = new CSharpParser(); var fileName = args[0]; CompilationUnit cu = null; try { using (var fs = new FileStream(fileName, FileMode.Open)) { cu = parser.Parse(fs); } } catch (DirectoryNotFoundException ex) { Console.WriteLine(ex.Message); Environment.Exit(-1); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); Environment.Exit(-1); } if (cu.Errors.Count > 0) { Console.WriteLine(string.Format("-> {0} is not a valid C# file.", fileName)); Console.WriteLine("-> Validation failed."); Environment.Exit(-1); } else { Console.WriteLine("-> Validation succeeded."); } Environment.Exit(0); }
private bool TryDecompileScript(FlowScript flowScript, out CompilationUnit compilationUnit) { // Evaluate script if (!TryEvaluateScript(flowScript, out var evaluationResult)) { LogError("Failed to evaluate script"); compilationUnit = null; return(false); } if (!TryDecompileScriptInternal(evaluationResult, out compilationUnit)) { LogError("Failed to decompile script"); compilationUnit = null; return(false); } return(true); }
/// <summary> /// Returns a sequence of suggestions on how errors for ambiguous types and callable in the given diagnostics can be fixed, /// given the file for which those diagnostics were generated and the corresponding compilation. /// Returns an empty enumerable if any of the given arguments is null. /// </summary> internal static IEnumerable <(string, WorkspaceEdit)> AmbiguousIdSuggestions( this FileContentManager file, CompilationUnit compilation, IEnumerable <Diagnostic> diagnostics) { if (file == null || diagnostics == null) { return(Enumerable.Empty <(string, WorkspaceEdit)>()); } var ambiguousCallables = diagnostics.Where(DiagnosticTools.ErrorType(ErrorCode.AmbiguousCallable)); var ambiguousTypes = diagnostics.Where(DiagnosticTools.ErrorType(ErrorCode.AmbiguousType)); if (!ambiguousCallables.Any() && !ambiguousTypes.Any()) { return(Enumerable.Empty <(string, WorkspaceEdit)>()); } (string, WorkspaceEdit)? SuggestedNameQualification(string suggestedNS, string?id, Position pos) { var edit = new TextEdit { Range = new Lsp.Range { Start = pos.ToLsp(), End = pos.ToLsp() }, NewText = $"{suggestedNS}." }; return(id is null ? null as (string, WorkspaceEdit)? : ($"{suggestedNS}.{id}", file.GetWorkspaceEdit(edit))); } var suggestedIdQualifications = ambiguousCallables .Select(d => d.Range.Start.ToQSharp()) .SelectMany(pos => file .IdNamespaceSuggestions(pos, compilation, out var id) .SelectNotNull(ns => SuggestedNameQualification(ns, id, pos))); var suggestedTypeQualifications = ambiguousTypes .Select(d => d.Range.Start.ToQSharp()) .SelectMany(pos => file .TypeNamespaceSuggestions(pos, compilation, out var id) .SelectNotNull(ns => SuggestedNameQualification(ns, id, pos))); return(suggestedIdQualifications.Concat(suggestedTypeQualifications)); }
public void PublicMethodInheritedProtected() { string program = TestUtil.GetInput(); string expected = TestUtil.GetExpected(); CompilationUnit cu = TestUtil.ParseProgram(program); TypesVisitor typesVisitor = new TypesVisitor(); typesVisitor.CodeBase = CodeBase; typesVisitor.VisitCompilationUnit(cu, null); CodeBase.Inheritors.Add("Test.Shape", "Test.SimpleShape"); CodeBase.Inheritors.Add("Test.Shape", "Test.PolygonShape"); CodeBase.Inheritors.Add("Test.SimpleShape", "Test.Rectangle"); CodeBase.Inheritors.Add("Test.PolygonShape", "Test.ComplexShape"); VisitCompilationUnit(cu, null); TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu)); }