private static void handleFunctionCall(Logic[] logicOrder, expectType theExpectedType, int lineNumber, Scope currentScope, int i) { FunctionParser.linkFunctionCall((logicOrder [i] as FunctionCall), lineNumber, currentScope); if ((logicOrder [i] as FunctionCall).targetFunc.isUserFunction) { currentScope.getCurrentLine().insertReturnExpect(logicOrder [i]); (logicOrder [i] as FunctionCall).runFunction(currentScope); throw new FunctionCallException(); } else { if ((logicOrder [i] as FunctionCall).targetFunc.pauseWalker) { CodeWalker.pauseWalker(); } if ((logicOrder[i] as FunctionCall).targetFunc.name == "input") { CodeWalker.linkSubmitInput.Invoke(SubmitInput, currentScope); Variable returnVariable = (logicOrder[i] as FunctionCall).runFunction(currentScope); logicOrder[i] = returnVariable; if (returnVariable.variableType == VariableTypes.boolean) { setNewExpectVariable(theExpectedType, VariableTypes.boolean, lineNumber); } else if (returnVariable.variableType == VariableTypes.number) { setNewExpectVariable(theExpectedType, VariableTypes.number, lineNumber); } else if (returnVariable.variableType == VariableTypes.textString) { setNewExpectVariable(theExpectedType, VariableTypes.textString, lineNumber); } CodeWalker.isWaitingForUserInput = true; } else { Variable returnVariable = (logicOrder[i] as FunctionCall).runFunction(currentScope); logicOrder[i] = returnVariable; if (returnVariable.variableType == VariableTypes.boolean) { setNewExpectVariable(theExpectedType, VariableTypes.boolean, lineNumber); } else if (returnVariable.variableType == VariableTypes.number) { setNewExpectVariable(theExpectedType, VariableTypes.number, lineNumber); } else if (returnVariable.variableType == VariableTypes.textString) { setNewExpectVariable(theExpectedType, VariableTypes.textString, lineNumber); } } } }
/// <summary> /// Walks through the code units in the query clause. /// </summary> /// <param name="statementCallback"> /// Callback executed when a statement is visited. /// </param> /// <param name="expressionCallback"> /// Callback executed when an expression is visited. /// </param> /// <param name="queryClauseCallback"> /// Callback executed when a query clause is visited. /// </param> public void WalkQueryClause( CodeWalkerStatementVisitor <object> statementCallback, CodeWalkerExpressionVisitor <object> expressionCallback, CodeWalkerQueryClauseVisitor <object> queryClauseCallback) { Param.Ignore(statementCallback, expressionCallback, queryClauseCallback); CodeWalker <object> .Start(this, statementCallback, expressionCallback, queryClauseCallback, null); }
/// <summary> /// Walks through the code units in the query clause. /// </summary> /// <param name="statementCallback"> /// Callback executed when a statement is visited. /// </param> /// <param name="expressionCallback"> /// Callback executed when an expression is visited. /// </param> /// <param name="queryClauseCallback"> /// Callback executed when a query clause is visited. /// </param> /// <param name="context"> /// The optional visitor context data. /// </param> /// <typeparam name="T"> /// The type of the context item. /// </typeparam> public void WalkQueryClause <T>( CodeWalkerStatementVisitor <T> statementCallback, CodeWalkerExpressionVisitor <T> expressionCallback, CodeWalkerQueryClauseVisitor <T> queryClauseCallback, T context) { Param.Ignore(statementCallback, expressionCallback, queryClauseCallback, context); CodeWalker <T> .Start(this, statementCallback, expressionCallback, queryClauseCallback, context); }
public static Logic parseContinueStatement(Logic[] logicOrder, int lineNumber, Scope currentScope) { //We use a shallow copy because we alter logicOrder in case of speciall operators Logic[] cloneLogicOrder = (Logic[])logicOrder.Clone(); if (cloneLogicOrder.Length != 1 || cloneLogicOrder[0].currentType != WordTypes.continueStatement) { return(new UnknownLogic(lineNumber)); } CodeWalker.continueLoop(findParentLoop(currentScope, lineNumber), lineNumber); return(new Variable()); }
static async Task Main(string[] args) { // Attempt to set the version of MSBuild. var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray(); var instance = visualStudioInstances.Length == 1 // If there is only one instance of MSBuild on this machine, set that as the one to use. ? visualStudioInstances[0] // Handle selecting the version of MSBuild you want to use. : SelectVisualStudioInstance(visualStudioInstances); Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects."); // NOTE: Be sure to register an instance with the MSBuildLocator // before calling MSBuildWorkspace.Create() // otherwise, MSBuildWorkspace won't MEF compose. MSBuildLocator.RegisterInstance(instance); using (var workspace = MSBuildWorkspace.Create()) { // Print message for WorkspaceFailed event to help diagnosing project load failures. workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message); var solutionPath = args[0]; Console.WriteLine($"Loading solution '{solutionPath}'"); // Attach progress reporter so we print projects as they are loaded. var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter()); var solutionName = Path.GetFileNameWithoutExtension(solutionPath); Console.WriteLine($"Finished loading solution '{solutionPath}'"); var nodes = new Dictionary <long, Node>(); var edges = new Dictionary <long, EdgeNode>(); foreach (var project in solution.Projects.Where(p => !p.Name.Contains("Test"))) { foreach (var document in project.Documents)//.Where(d=>!d.Name.Contains("Dummy"))) { var collector = new CodeWalker(document.FilePath, document.Name, nodes, edges); SyntaxTree tree = CSharpSyntaxTree.ParseText(await document.GetTextAsync()); var root = (CompilationUnitSyntax)tree.GetRoot(); collector.Visit(root); } } // Save Data files new Exporter(nodes, edges) //.ExportJson(solutionName) //.ExportNeo4J(solutionName) .ExportCsv(solutionName); } }
/// <summary> /// Private helper function for all parsing. Takes in the IronPython Parser /// object and a filename that's used for error reports /// </summary> /// <param name="p"></param> private CodeCompileUnit Parse(Parser p, string filename) { Stmt s = p.ParseFileInput(); CodeCompileUnit res = new CodeCompileUnit(); CodeNamespace defaultNamespace = new CodeNamespace(); //!!! enable AD usage when we're strong named. //AppDomainSetup ads = new AppDomainSetup(); //ads.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //AppDomain ad = AppDomain.CreateDomain("ParserReferenceDomain",null,ads); try { RemoteReferences rc = new RemoteReferences(); /*(RemoteReferences)ad.CreateInstanceAndUnwrap( * Assembly.GetExecutingAssembly().FullName, * "IronPython.CodeDom.RemoteReferences");*/ rc.Initialize(references); CodeWalker cw = new CodeWalker(filename, rc); s.Walk(cw); CodeObject co = cw.LastObject; CodeObjectSuite cos = co as CodeObjectSuite; if (cos == null) { cos = new CodeObjectSuite(new CodeObject[] { co }); } // walk the top-level and see if we need to create a fake top-type // or if we can just stick everything directly into the namespace. CodeTypeDeclaration topType = null; for (int i = 0; i < cos.Count; i++) { topType = CheckTopLevel(cos[i], res, defaultNamespace, topType); } // if no namespaces we're added then everything's in our default namespace. if (res.Namespaces.Count == 0) { res.Namespaces.Add(defaultNamespace); } UpdateTopType(topType, defaultNamespace); } finally { //AppDomain.Unload(ad); } return(res); }
public static void SubmitInput(string inputFromUser, Scope currentScope) { if (!CodeWalker.isWaitingForUserInput) { return; } CodeWalker.isWaitingForUserInput = false; var oldLine = currentScope.getCurrentLine().cloneLine(); var oldLineString = oldLine.getFullLine(); var newLine = ReplaceInputWithValue(oldLineString, inputFromUser); var lines = SyntaxCheck.parseLines(newLine); var words = lines.First().words; var logic = WordsToLogicParser.determineLogicFromWords(words, 1, currentScope); currentScope.getCurrentLine().words = words; currentScope.getCurrentLine().logicOrder = logic; CodeWalker.parseLine(currentScope.getCurrentLine(), oldLine); }
/// <summary> /// Renders the C# code text to the specified <see cref="TextWriter" />. /// </summary> /// <remarks> /// The version of the <c>Render</c> method does all of the work because the other versions ultimately call this one. The /// steps involved are: /// <list type="number"> /// <item><description> /// The code text is parsed to produce a <c>SyntaxTree</c> /// </description></item> /// <item><description> /// A compilation unit is created from the <c>SyntaxTree</c> and <c>MetadataReferences</c> properties and from that /// the <c>SemanticModel</c> is initialized. Note that renderers that are only interested in the syntax need not /// access the semantic mode, but the HTML renderer does need this information to determine if an identifier represents /// a symbol that should be (color) formatted. /// </description></item> /// <item><description> /// The <c>SyntaxVisiting</c> event is handled by invoking the <c>Callback</c> passing the <c>SyntaxTreeElement</c> /// object and <c>VisitingState</c> enumeration value encapsulated in the <c>SyntaxVisitingEventArgs</c> object. /// Concrete implementations due the actual rendering from the callback delegate. /// </description></item> /// <item><description> /// Any prefix text is recovered using the <c>GetPrefixText</c> method and is written to the <c>Writer</c>. /// </description></item> /// <item><description> /// The syntax tree root node is passed to the <c>SyntaxWalker.Visit</c> method (really the overridden /// <c>SyntaxVisitor.Visit</c> method. This causes the callback delegate to be called as the tree is traversed. From /// the callback delegate, concrete implementations can write to the <c>Writer</c> to render the nodes, tokens and /// trivia that make up the syntax tree. /// </description></item> /// <item><description> /// Finally, any postfix text is recovered using the <c>GetPostfixText</c> method and is written to the <c>Writer</c>. /// </description></item> /// </list> /// </remarks> /// <param name="writer">The <c>TextWriter</c> which contains the rendered code. It is the responsibility of the /// caller to dispose of the <paramref name="writer" /> when it is no longer needed. </param> /// <param name="codeText">The code text as a <see cref="string" /> instance.</param> /// <exception cref="ArgumentNullException">if <paramref name="writer"/> is null.</exception> public virtual void Render(TextWriter writer, string codeText) { if (writer == null) { throw new ArgumentNullException(nameof(writer), "A non-null TextWriter is required."); } Writer = writer; SyntaxTree = CSharpSyntaxTree.ParseText(codeText ?? string.Empty); // TODO: Formatting no longer provides a extension method on nodes. Move the entire functionality to another namespace. // if (FormatCode) // { // IFormattingResult formattingResult = SyntaxTree.GetRoot().Format(FormattingOptions.GetDefaultOptions()); // CompilationUnitSyntax formattedRoot = (CompilationUnitSyntax)formattingResult.GetFormattedRoot(); // SyntaxTree = SyntaxTree.Create(formattedRoot); // } Compilation compilation = CSharpCompilation.Create("CoreRenderer", syntaxTrees: new List <SyntaxTree> { SyntaxTree }, references: MetadataReferences); SemanticModel = compilation.GetSemanticModel(SyntaxTree); CodeWalker walker = new CodeWalker(); walker.SyntaxVisiting += (s, e) => { if (Callback != null) { Callback(e.SyntaxTreeElement, e.State); } }; Writer.Write(GetPrefixText()); walker.Visit(SyntaxTree.GetRoot()); Writer.Write(GetPostfixText()); }
public static Logic parseReturnStatement(Logic[] logicOrder, int lineNumber, Scope currentScope) { if (logicOrder.Length <= 1) { } Variable returnSum; if (logicOrder.Length <= 1) { // Should return None if there is no sum to return returnSum = new Variable(); //This error should not exist ErrorMessage.sendErrorMessage(lineNumber, "I detta moment måste du returnera något ur funktionen"); } else { Logic[] followOrder = InternalParseFunctions.getSubArray(logicOrder, 1, logicOrder.Length - 1, lineNumber); returnSum = SumParser.parseIntoSum(followOrder, lineNumber, currentScope); } ReturnStatement theReturn = (logicOrder [0] as ReturnStatement); theReturn.findFunctionParent(currentScope, lineNumber); CodeLine parentLine = theReturn.FunctionParent.parentScope.codeLines [theReturn.FunctionParent.parentScope.lastReadLine]; ReturnMemoryControll.insertReturnValue(parentLine, lineNumber, returnSum); currentScope.isReturning = true; CodeWalker.setReturnTarget(theReturn.FunctionParent.parentScope); return(logicOrder [0] as ReturnStatement); }
public LoopUnrollingResults Unroll() { var unrolled = new DILOperationSet(); //if (IsClearanceLoop()) //{ // unrolled.Add(new AssignOp(0, 0)); // return new LoopUnrollingResults(unrolled, true); //} var withUnrolledNestLoops = new DILOperationSet(); foreach (var instruction in Instructions) { if (instruction is LoopOp) { var nestedLoop = instruction as LoopOp; var ur = nestedLoop.Unroll(); if (ur.WasLoopUnrolled) { withUnrolledNestLoops.AddRange(ur.UnrolledInstructions); } else { withUnrolledNestLoops.Add(new LoopOp(ur.UnrolledInstructions)); } } else { withUnrolledNestLoops.Add(instruction); } } if (IsSimple(withUnrolledNestLoops)) { var walk = new CodeWalker().Walk(withUnrolledNestLoops); if (walk.Domain.ContainsKey(0) && walk.Domain[0] == -1) { foreach (var cell in walk.Domain) { if (cell.Key == 0) { continue; } //// If the scalar value of the multiplication operation is 0, //// then simply assign 0 to the cell because n * 0 = 0. //if (cell.Value == 0) //{ // unrolled.Add(new AssignOp(cell.Key, 0)); //} //else //{ unrolled.Add(new MultiplicationMemoryOp(cell.Key, cell.Value)); //} } // If it's a simple loop, then the cell position of the loop should always be assigned a 0 since that's when the loop stops. if (walk.Domain.ContainsKey(0)) { unrolled.Add(new AssignOp(0, 0)); } return new LoopUnrollingResults(unrolled, true); } else { return new LoopUnrollingResults(withUnrolledNestLoops, false); } } return new LoopUnrollingResults(withUnrolledNestLoops, false); }
/// <summary> /// Private helper function for all parsing. Takes in the IronPython Parser /// object and a filename that's used for error reports /// </summary> /// <param name="p"></param> private CodeCompileUnit Parse(Parser p, string filename) { Statement s = p.ParseFileInput(); CodeCompileUnit res = new CodeCompileUnit(); CodeNamespace defaultNamespace = new CodeNamespace(); defaultNamespace.UserData["Line"] = 1; defaultNamespace.UserData["Column"] = 1; defaultNamespace.UserData["EndLine"] = 1; defaultNamespace.UserData["EndColumn"] = 1; //!!! enable AD usage when we're strong named. //AppDomainSetup ads = new AppDomainSetup(); //ads.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //AppDomain ad = AppDomain.CreateDomain("ParserReferenceDomain",null,ads); try { RemoteReferences rc = new RemoteReferences(); /*(RemoteReferences)ad.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, "IronPython.CodeDom.RemoteReferences");*/ rc.Initialize(references); CodeWalker cw = new CodeWalker(filename, rc); s.Walk(cw); CodeObject co = cw.LastObject; CodeObjectSuite cos = co as CodeObjectSuite; if (cos == null) cos = new CodeObjectSuite(new CodeObject[] { co }); // walk the top-level and see if we need to create a fake top-type // or if we can just stick everything directly into the namespace. CodeTypeDeclaration topType = null; for (int i = 0; i < cos.Count; i++) { topType = CheckTopLevel(cos[i], res, defaultNamespace, topType); } // if no namespaces we're added then everything's in our default namespace. if (res.Namespaces.Count == 0 || defaultNamespace.Types.Count > 0) { res.Namespaces.Add(defaultNamespace); } UpdateTopType(topType, defaultNamespace); } finally { //AppDomain.Unload(ad); } return res; }
public LoopUnrollingResults Unroll() { var unrolled = new DILOperationSet(); //if (IsClearanceLoop()) //{ // unrolled.Add(new AssignOp(0, 0)); // return new LoopUnrollingResults(unrolled, true); //} var withUnrolledNestLoops = new DILOperationSet(); foreach (var instruction in Instructions) { if (instruction is LoopOp) { var nestedLoop = instruction as LoopOp; var ur = nestedLoop.Unroll(); if (ur.WasLoopUnrolled) { withUnrolledNestLoops.AddRange(ur.UnrolledInstructions); } else { withUnrolledNestLoops.Add(new LoopOp(ur.UnrolledInstructions)); } } else { withUnrolledNestLoops.Add(instruction); } } if (IsSimple(withUnrolledNestLoops)) { var walk = new CodeWalker().Walk(withUnrolledNestLoops); if (walk.Domain.ContainsKey(0) && walk.Domain[0] == -1) { foreach (var cell in walk.Domain) { if (cell.Key == 0) { continue; } //// If the scalar value of the multiplication operation is 0, //// then simply assign 0 to the cell because n * 0 = 0. //if (cell.Value == 0) //{ // unrolled.Add(new AssignOp(cell.Key, 0)); //} //else //{ unrolled.Add(new MultiplicationMemoryOp(cell.Key, cell.Value)); //} } // If it's a simple loop, then the cell position of the loop should always be assigned a 0 since that's when the loop stops. if (walk.Domain.ContainsKey(0)) { unrolled.Add(new AssignOp(0, 0)); } return(new LoopUnrollingResults(unrolled, true)); } else { return(new LoopUnrollingResults(withUnrolledNestLoops, false)); } } return(new LoopUnrollingResults(withUnrolledNestLoops, false)); }