public static INode snippetParser_Parse(this string code)
 {
     if(code.notValid())
         return null;
     var snippetParser = new SnippetParser(SupportedLanguage.CSharp);             
     return snippetParser.Parse(code);
 }
예제 #2
0
        public JsFile GetJsFileFromCodeSnippet(string codeSnippet, SupportedLanguage language)
        {
            var file = new JsFile();

            var snippetParser = new SnippetParser(language);

            var jsFile = new JsFile
            {
                FullPath = string.Empty
            };

            var parsedNode = snippetParser.Parse(codeSnippet);

            if (parsedNode.Children.Count > 0)
            {
                var visitor = new AstVisitor
                {
                    Model = jsFile
                };

                parsedNode.AcceptVisitor(visitor, null);

                file = visitor.Model;
                return file;
            }

            return null;
        }
		INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error)
		{
			project = new DefaultProjectContent();
			project.ReferencedContents.AddRange(ReferencedContents);
			if (sourceLanguage == SupportedLanguage.VBNet) {
				project.Language = LanguageProperties.VBNet;
				project.DefaultImports = new DefaultUsing(project);
				project.DefaultImports.Usings.AddRange(DefaultImportsToAdd);
			} else {
				project.Language = LanguageProperties.CSharp;
			}
			SnippetParser parser = new SnippetParser(sourceLanguage);
			INode result = parser.Parse(sourceCode);
			error = parser.Errors.ErrorOutput;
			specials = parser.Specials;
			if (parser.Errors.Count != 0)
				return null;
			
			wasExpression = parser.SnippetType == SnippetType.Expression;
			if (wasExpression) {
				// Special case 'Expression': expressions may be replaced with other statements in the AST by the ConvertVisitor,
				// but we need to return a 'stable' node so that the correct transformed AST is returned.
				// Thus, we wrap any expressions into a statement block.
				result = MakeBlockFromExpression((Expression)result);
			}
			
			// now create a dummy compilation unit around the snippet result
			switch (parser.SnippetType) {
				case SnippetType.CompilationUnit:
					compilationUnit = (CompilationUnit)result;
					break;
				case SnippetType.Expression:
				case SnippetType.Statements:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							(BlockStatement)result
						));
					break;
				case SnippetType.TypeMembers:
					compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children);
					break;
				default:
					throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType);
			}
			
			// convert NRefactory CU in DOM CU
			NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project);
			visitor.VisitCompilationUnit(compilationUnit, null);
			visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb";
			
			// and register the compilation unit in the DOM
			foreach (IClass c in visitor.Cu.Classes) {
				project.AddClassToNamespaceList(c);
			}
			parseInfo = new ParseInformation();
			parseInfo.SetCompilationUnit(visitor.Cu);
			
			return result;
		}
        public static string ast_CSharp_CreateCompilableClass(this string codeSnippet)
        {
            var snippetParser   = new SnippetParser(SupportedLanguage.CSharp);
            var iNode           = snippetParser.Parse(codeSnippet);

            return iNode.cast<BlockStatement>()
                .ast_CSharp_CreateCompilableClass(snippetParser, codeSnippet);
        }
		INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error)
		{
			project = new DefaultProjectContent();
			project.ReferencedContents.AddRange(ReferencedContents);
			if (sourceLanguage == SupportedLanguage.VBNet) {
				project.DefaultImports = new DefaultUsing(project);
				project.DefaultImports.Usings.AddRange(DefaultImportsToAdd);
			}
			SnippetParser parser = new SnippetParser(sourceLanguage);
			INode result = parser.Parse(sourceCode);
			error = parser.Errors.ErrorOutput;
			specials = parser.Specials;
			if (parser.Errors.Count != 0)
				return null;
			
			// now create a dummy compilation unit around the snippet result
			switch (parser.SnippetType) {
				case SnippetType.CompilationUnit:
					compilationUnit = (CompilationUnit)result;
					break;
				case SnippetType.Expression:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							MakeBlockFromExpression(
								(Expression)result
							)));
					break;
				case SnippetType.Statements:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							(BlockStatement)result
						));
					break;
				case SnippetType.TypeMembers:
					compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children);
					break;
				default:
					throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType);
			}
			
			// convert NRefactory CU in DOM CU
			NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project);
			visitor.VisitCompilationUnit(compilationUnit, null);
			visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb";
			
			// and register the compilation unit in the DOM
			foreach (IClass c in visitor.Cu.Classes) {
				project.AddClassToNamespaceList(c);
			}
			parseInfo = new ParseInformation();
			parseInfo.SetCompilationUnit(visitor.Cu);
			
			return result;
		}
        public static string ast_CSharp_CreateCompilableClass(this BlockStatement blockStatement, SnippetParser snippetParser, string codeSnippet)
        {
            if (blockStatement.isNull() || snippetParser.isNull() || codeSnippet.notValid())
                return null;

            var compilerOptions   = new CSharp_FastCompiler_CompilerOptions  ();
            var compilerArtifacts = new CSharp_FastCompiler_CompilerArtifacts();
            var executionOptions  = new CSharp_FastCompiler_ExecutionOptions ();
            var csharpCode        = blockStatement.ast_CSharp_CreateCompilableClass(snippetParser, codeSnippet,
                compilerOptions, compilerArtifacts, executionOptions);
            return csharpCode;
        }
        public static string ast_CSharp_CreateCompilableClass(this BlockStatement blockStatement, SnippetParser snippetParser, string codeSnippet,
            CSharp_FastCompiler_CompilerOptions   compilerOptions,
            CSharp_FastCompiler_CompilerArtifacts compilerArtifacts,
            CSharp_FastCompiler_ExecutionOptions  executionOptions)
        {
            if (blockStatement.isNull() || compilerOptions.isNull())
                return null;

            var compilationUnit= compilerArtifacts.CompilationUnit = new CompilationUnit();

            compilationUnit.add_Type(compilerOptions.default_TypeName)
                .add_Method(compilerOptions.default_MethodName, executionOptions.InvocationParameters,
                    compilerOptions.ResolveInvocationParametersType, blockStatement);

            // remove comments from parsed code
            var astCSharp = compilerArtifacts.AstCSharp = new Ast_CSharp(compilerArtifacts.CompilationUnit, snippetParser.Specials);

            // add references included in the original source code file
            compilerArtifacts.AstCSharp.mapCodeO2References(compilerOptions);

            astCSharp.mapAstDetails();

            astCSharp.ExtraSpecials.Clear();
            var method     = compilationUnit.method(compilerOptions.default_MethodName);
            var returntype = method.returnType();
            var type       = compilationUnit.type(compilerOptions.default_TypeName);

            type.Children.Clear();
            var tempBlockStatement = new BlockStatement();
            tempBlockStatement.add_Variable("a", 0);
            method.Body = tempBlockStatement;
            var newMethod = type.add_Method(compilerOptions.default_MethodName, executionOptions.InvocationParameters,
                compilerOptions.ResolveInvocationParametersType, tempBlockStatement);
            newMethod.TypeReference = returntype;

            if(blockStatement.returnStatements().size() >1)
                astCSharp.methodDeclarations().first().remove_LastReturnStatement();

            astCSharp.mapAstDetails();

            var codeToReplace = "Int32 a = 0;";
            var csharpCode = astCSharp.AstDetails.CSharpCode
                .replace("\t\t{0}".format(codeToReplace), codeToReplace)    // remove tabs
                .replace("Int32 a = 0;", codeSnippet);                      // put the actual code (this should be done via AST, but it was affectting code complete)
            return csharpCode;
        }
예제 #8
0
		/// <returns> Returned value or null for statements </returns>
		public static Value Evaluate(string code, SupportedLanguage language, StackFrame context)
		{
			SnippetParser parser = new SnippetParser(language);
			INode astRoot = parser.Parse(code);
			if (parser.SnippetType == SnippetType.Expression ||
			    parser.SnippetType == SnippetType.Statements) {
				if (parser.Errors.Count > 0) {
					throw new GetValueException(parser.Errors.ErrorOutput);
				}
				try {
					EvaluateAstVisitor visitor = new EvaluateAstVisitor(context);
					
					return astRoot.AcceptVisitor(visitor, null) as Value;
				} catch (NotImplementedException e) {
					throw new GetValueException("Language feature not implemented: " + e.Message);
				}
			}
			throw new GetValueException("Code must be expression or statement");
		}
예제 #9
0
        //this code needs to be completely rewritten
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
                return null;
            code = code.line();	// make sure there is an empty line at the end

            try
            {
                //handle special incudes in source code
                var lines = code.fix_CRLF().lines();
                foreach (var originalLine in lines)
                {
                    string line = originalLine;
                    originalLine.starts("//O2Include:", (includeText) =>
                        {
                            var file = includeText;
                            var baseFile = SourceCodeFile ?? PublicDI.CurrentScript;
                            var parentFolder = baseFile.parentFolder();
                            if (parentFolder.notValid())
                                "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error();
                            var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file,parentFolder);
                            if (resolvedFile.fileExists())
                            {
                                var fileContents = resolvedFile.contents();
                                code = code.Replace(line, line.line().add(fileContents).line());
                            }
                            else
                                "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText);
                        });
                }

                var snippetParser = new SnippetParser(SupportedLanguage.CSharp);

                var parsedCode = snippetParser.Parse(code);
                AstErrors = snippetParser.errors();
                CompilationUnit = new CompilationUnit();

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method
                        var blockStatement = (BlockStatement)parsedCode;
                        CompilationUnit.add_Type(default_TypeName)
                            .add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, blockStatement);

                        // remove comments from parsed code
                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);

                        // add references included in the original source code file
                        mapCodeO2References(astCSharp);

                        astCSharp.mapAstDetails();

                        astCSharp.ExtraSpecials.Clear();
                        var method = CompilationUnit.method(default_MethodName);
                        var returntype = method.returnType();
                        var type = CompilationUnit.type(default_TypeName);

                        type.Children.Clear();
                        var tempBlockStatement = new BlockStatement();
                        tempBlockStatement.add_Variable("a", 0);
                        method.Body = tempBlockStatement;
                        var newMethod = type.add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, tempBlockStatement);
                        newMethod.TypeReference = returntype;
                        astCSharp.mapAstDetails();
                        var csharpCode = astCSharp.AstDetails.CSharpCode
                                                  .replace("Int32 a = 0;", code);

                        AstDetails = new Ast_CSharp(csharpCode).AstDetails;
                        CreatedFromSnipptet = true;
                        DebugMode.ifDebug("Ast parsing was OK");
                        SourceCode = csharpCode;
                        onAstOK.invoke();

                        return csharpCode;
                    }

                    CompilationUnit = (CompilationUnit)parsedCode;
                    if (CompilationUnit.Children.Count == 0)
                        return null;

                    astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                    // add the comments from the original code

                    mapCodeO2References(astCSharp);
                    CreatedFromSnipptet = false;

                    // create sourceCode using Ast_CSharp & AstDetails
                    if(CompilationUnit.Children.Count > 0)
                    {
                        // reset the astCSharp.AstDetails object
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);

                        SourceCode = astCSharp.AstDetails.CSharpCode;

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        AstDetails = tempAstDetails;
                        DebugMode.ifDebug("Ast parsing was OK");
                        onAstOK.invoke();
                        return SourceCode;
                    }
                }
            }
            catch (Exception ex)
            {
                DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);
            }
            return null;
        }
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
                return null;
			code = code.line();	// make sure there is an empty line at the end            
                      
            try
            {
                // handle special incudes in source code
                foreach(var originalLine in code.lines())
                    originalLine.starts("//include", (includeText) => 
                        {
                            if (includeText.fileExists())
                                code = code.Replace(originalLine, originalLine.line().add(includeText.contents()));
                        });  
            	var snippetParser = new SnippetParser(SupportedLanguage.CSharp);
                
                var parsedCode = snippetParser.Parse(code);
				AstErrors = snippetParser.errors();
                CompilationUnit = new CompilationUnit();

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method 

                        var blockStatement = (BlockStatement)parsedCode;
                        CompilationUnit.add_Type(default_TypeName)
                            .add_Method(default_MethodName, InvocationParameters, blockStatement);

                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                        //astCSharp.AstDetails.mapSpecials();

                        // add references included in the original source code file
                        mapCodeO2References(astCSharp);

                        CreatedFromSnipptet = true;
                    }
                    else
                    {
                        CompilationUnit = (CompilationUnit)parsedCode;
                        if (CompilationUnit.Children.Count == 0)
                            return null;

                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                        // add the comments from the original code                        

                        mapCodeO2References(astCSharp);
                        CreatedFromSnipptet = false;
                    }
                    
                    // create sourceCode using Ast_CSharp & AstDetails		
                    if(CompilationUnit.Children.Count > 0)
                    {                        
                        // reset the astCSharp.AstDetails object        	
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);	                 

	                    SourceCode = astCSharp.AstDetails.CSharpCode;

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        AstDetails = tempAstDetails;
	                    DebugMode.ifDebug("Ast parsing was OK");
	                    this.invoke(onAstOK);
	                    return SourceCode;
                    }
                }            
            }
            catch (Exception ex)
            {                            	
				DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);                
            }      			
			return null;                
        }        
예제 #11
0
        ///                
        /// <summary>
        /// Returns a compilable C# file from and Snippet
        /// 
        /// Dev Note:this code needs to be refactored (since it is too big and complex)
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
                return null;
            code = code.line();	// make sure there is an empty line at the end

            try
            {
                //handle special incudes in source code
                var lines = code.fix_CRLF().lines();
                foreach (var originalLine in lines)
                {
                    var line = originalLine;
                    if(originalLine.starts("//O2Include:"))
                    {
                        var includeText = line.subString_After("//O2Include:");
                        var file = includeText;
                        var baseFile = CompilerOptions.SourceCodeFile ?? PublicDI.CurrentScript;
                        var parentFolder = baseFile.parentFolder();
                        if (parentFolder.notValid())
                            "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error();
                        var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file,parentFolder);
                        if (resolvedFile.fileExists())
                        {
                            var fileContents = resolvedFile.contents();
                            code = code.Replace(line, line.line().add(fileContents).line());
                        }
                        else
                            "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText);
                    };
                }

                var snippetParser = new SnippetParser(SupportedLanguage.CSharp);

                var parsedCode = snippetParser.Parse(code);
                this.astErrors(snippetParser.errors());

                this.compilationUnit(new CompilationUnit());

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method
                        var blockStatement = (BlockStatement)parsedCode;

                        var csharpCode = blockStatement.ast_CSharp_CreateCompilableClass(snippetParser, code,
                                                                                         CompilerOptions, CompilerArtifacts, ExecutionOptions);

                        this.astDetails(new Ast_CSharp(csharpCode).AstDetails);
                        this.createdFromSnippet(true);
                        DebugMode.ifDebug("Ast parsing was OK");
                        this.sourceCode(csharpCode);
                        this.raise_OnAstOK();

                        return csharpCode;
                    }

                    this.compilationUnit((CompilationUnit)parsedCode);
                    if (this.compilationUnit().Children.Count == 0)
                        return null;

                    astCSharp = new Ast_CSharp(this.compilationUnit(), snippetParser.Specials);
                    // add the comments from the original code

                    astCSharp.mapCodeO2References(CompilerOptions);
                    this.createdFromSnippet(false);

                    // create sourceCode using Ast_CSharp & AstDetails
                    if(this.compilationUnit().Children.Count > 0)
                    {
                        // reset the astCSharp.AstDetails object
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);

                        this.sourceCode(astCSharp.AstDetails.CSharpCode);

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(this.sourceCode()).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        this.astDetails(tempAstDetails);
                        DebugMode.ifDebug("Ast parsing was OK");
                        this.raise_OnAstOK();
                        return this.sourceCode();
                    }
                }
            }
            catch (Exception ex)
            {
                DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);
            }
            return null;
        }