private void WireUpJavaScriptConfigurationObject(CSharp.Context context) { var prototype = context.Environment.NewObject(); var constructor = IronJS.Native.Utils.CreateConstructor<Func<FunctionObject, CommonObject, CommonObject>>( context.Environment, 0, (ctor, _) => { var proto = ctor.GetT<CommonObject>("prototype"); return new ConfigJsObject(ctor.Env, this, proto); }); prototype.Prototype = context.Environment.Prototypes.Object; prototype.Put("run", IronJS.Native.Utils.CreateFunction<Action<FunctionObject, CommonObject, BoxedValue>>( context.Environment, 1, ConfigJsObject.Run)); prototype.Put("use", IronJS.Native.Utils.CreateFunction<Action<FunctionObject, CommonObject, CommonObject>>( context.Environment, 1, ConfigJsObject.Use)); prototype.Put("map", IronJS.Native.Utils.CreateFunction<Action<FunctionObject, CommonObject, string, BoxedValue>>( context.Environment, 1, ConfigJsObject.Map)); constructor.Put("prototype", prototype); context.SetGlobal("Config", constructor); }
private static FunctionObject LoadUglify(CSharp.Context context, ResourceHelper resourceHelper) { string uglifyCode = resourceHelper.Get("uglify-js.js"); context.Execute(String.Concat(uglifyCode)); return context.GetGlobalAs<FunctionObject>("uglify"); }
public CreateHandler( CSharp.Files.IResolveFileTypes fileTypeResolver, string keyPath) { _fileTypeResolver = fileTypeResolver; _keyPath = keyPath; }
public SetupForm(CSharp aCSharp, IItemBrowser aBrowser) { mCSharp = aCSharp; mBrowser = aBrowser; InitializeComponent(); fastColoredTextBox_Code.Text = mCSharp.Code; Size = mCSharp.mEditorSize; mNormalSize = mCSharp.mEditorSize; splitContainerControl_Code.SplitterPosition = mCSharp.mEditorSplitterPos; tsComboBox_Font.SelectedIndex = mCSharp.mEditorFontIndex; mAutocompleteMenu = new AutocompleteMenu(fastColoredTextBox_Code); mAutocompleteMenu.SelectedColor = Color.Green; var lItems = mBrowser.TotalItemNames; string lMaxName = ""; for (int i = 0; i < lItems.Length; i++) { if (lMaxName.Length < lItems[i].Length) lMaxName = lItems[i]; } var lWidth = TextRenderer.MeasureText(lMaxName, mAutocompleteMenu.Font).Width; lWidth = lWidth + lWidth / 5; mAutocompleteMenu.Items.MaximumSize = new System.Drawing.Size(lWidth, 300); mAutocompleteMenu.Items.Width = lWidth; mAutocompleteMenu.Items.SetAutocompleteItems(lItems); TriggerTimeMS = mCSharp.mTriggerTimeMS; WatchdogMS = mCSharp.mWatchdogMS; }
public static new FunctionObject Create(CSharp.Context context) { var ctor = Utils.CreateConstructor( context.Environment, 0, (Func<FunctionObject, CommonObject, CommonObject>)Construct); ctor.Put("prototype", CreatePrototype(context)); return ctor; }
private static FunctionObject LoadUglify(CSharp.Context context, ResourceHelper resourceHelper) { const string defineModule = "var module = {};"; string uglifyCode = resourceHelper.Get("uglify-js.js"); context.Execute(String.Concat(defineModule, uglifyCode)); return context.GetGlobalAs<FunctionObject>("uglify"); }
/// <summary> /// Initializes a new instance of the <see cref="RequireDefinition"/> class. /// </summary> /// <param name="context">The context.</param> /// <param name="resourceHelper">The resource helper.</param> public RequireDefinition(CSharp.Context context, ResourceHelper resourceHelper) { if (context == null) throw new ArgumentNullException("context"); if (resourceHelper == null) throw new ArgumentNullException("resourceHelper"); this.context = context; this.resourceHelper = resourceHelper; this.requireCache = new Dictionary<string, CommonObject>(); this.cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); this.require = Utils.CreateFunction<Func<string, CommonObject>>(this.context.Environment, 1, Require); }
public Blender(Lexer lexer, CSharp.CSharpSyntaxNode oldTree, IEnumerable<TextChangeRange> changes) { Debug.Assert(lexer != null); _lexer = lexer; _changes = ImmutableStack.Create<TextChangeRange>(); if (changes != null) { // TODO: Consider implementing NormalizedChangeCollection for TextSpan. the real // reason why we are collapsing is because we want to extend change ranges and // cannot allow them to overlap. This does not seem to be a big deal since multiple // changes are infrequent and typically close to each other. However if we have // NormalizedChangeCollection for TextSpan we can have both - we can extend ranges // and not require collapsing them. NormalizedChangeCollection would also ensure // that changes are always normalized. // TODO: this is a temporary measure to prevent individual change spans from // overlapping after they are widened to effective width (+1 token at the start). // once we have normalized collection for TextSpan we will not need to collapse all // the change spans. var collapsed = TextChangeRange.Collapse(changes); // extend the change to its affected range. This will make it easier // to filter out affected nodes since we will be able simply check // if node intersects with a change. var affectedRange = ExtendToAffectedRange(oldTree, collapsed); _changes = _changes.Push(affectedRange); } if (oldTree == null) { // start at lexer current position if no nodes specified _oldTreeCursor = new Cursor(); _newPosition = lexer.TextWindow.Position; } else { _oldTreeCursor = Cursor.FromRoot(oldTree).MoveToFirstChild(); _newPosition = 0; } _changeDelta = 0; _newDirectives = default(DirectiveStack); _oldDirectives = default(DirectiveStack); _newLexerDrivenMode = 0; }
public static void AttachToContext(CSharp.Context context) { CommonObject prototype = context.Environment.NewObject(); FunctionObject constructor = Utils.CreateConstructor<Func<FunctionObject, CommonObject, CommonObject>> (context.Environment, 0, Construct); FunctionObject log = Utils.CreateFunction<Action<FunctionObject, CommonObject, object>> (context.Environment, 1, ConsoleObject.Log); FunctionObject dir = Utils.CreateFunction<Action<FunctionObject, CommonObject, object>> (context.Environment, 1, ConsoleObject.Dir); prototype.Prototype = context.Environment.Prototypes.Object; prototype.Put("log", log, DescriptorAttrs.Immutable); prototype.Put("dir", dir, DescriptorAttrs.Immutable); constructor.Put("prototype", prototype, DescriptorAttrs.Immutable); context.SetGlobal("Console", constructor); context.Execute("console = new Console();"); }
public static CommonObject CreatePrototype(CSharp.Context context) { var addHandler = Utils.CreateFunction( context.Environment, 2, (Action<FunctionObject, CommonObject, string, FunctionObject>)AddHandler); var removeHandler = Utils.CreateFunction( context.Environment, 2, (Action<FunctionObject, CommonObject, string, FunctionObject>)RemoveHandler); var trigger = Utils.CreateFunction( context.Environment, 2, (Action<FunctionObject, CommonObject, string, BoxedValue>)Trigger); var prototype = context.Environment.NewObject(); prototype.Prototype = context.Environment.Prototypes.Object; prototype.Put("addHandler", addHandler); prototype.Put("removeHandler", removeHandler); prototype.Put("trigger", trigger); return prototype; }
public static void AttachToContext(CSharp.Context context, IMainWindow window) { var jsWindow = new WindowObject( context.Environment, context.Environment.Prototypes.Object, window); var setTitle = Utils.CreateFunction( context.Environment, 1, (Action<FunctionObject, CommonObject, string>)SetTitle); var getTitle = Utils.CreateFunction( context.Environment, 0, (Func<FunctionObject, CommonObject, string>)GetTitle); var addCommand = Utils.CreateFunction( context.Environment, 1, (Action<FunctionObject, CommonObject, CommonObject>)AddCommand); var removeCommand = Utils.CreateFunction( context.Environment, 1, (Action<FunctionObject, CommonObject, CommonObject>)RemoveCommand); var addApplicationCommand = Utils.CreateFunction( context.Environment, 1, (Action<FunctionObject, CommonObject, CommonObject>)AddApplicationCommand); var removeApplicationCommand = Utils.CreateFunction( context.Environment, 1, (Action<FunctionObject, CommonObject, CommonObject>)RemoveApplicationCommand); var exit = Utils.CreateFunction( context.Environment, 0, (Action<FunctionObject, CommonObject>)Exit); var editors = new EditorProviderObject(context.Environment, context.Environment.Prototypes.Object, window.Editors); jsWindow.Put("setTitle", setTitle, DescriptorAttrs.Immutable); jsWindow.Put("getTitle", getTitle, DescriptorAttrs.Immutable); jsWindow.Put("addCommand", addCommand, DescriptorAttrs.Immutable); jsWindow.Put("removeCommand", removeCommand, DescriptorAttrs.Immutable); jsWindow.Put("addApplicationCommand", addApplicationCommand, DescriptorAttrs.Immutable); jsWindow.Put("removeApplicationCommand", removeApplicationCommand, DescriptorAttrs.Immutable); jsWindow.Put("exit", exit, DescriptorAttrs.Immutable); jsWindow.Put("editors", editors, DescriptorAttrs.Immutable); context.SetGlobal("window", jsWindow); }
public static SLE.Expression ConvertMethod(SLE.Expression [] parameters, MethodDefinition method) { var body = method.Body.Decompile(CSharp.GetLanguage(CSharpVersion.V1)); if (body.Statements.Count != 1) { throw new ArgumentException(); } var @return = body.Statements [0] as ReturnStatement; if (@return == null) { throw new ArgumentException(); } var converter = new ExpressionConverter(parameters, method); converter.Visit(@return.Expression); return(converter.Pop()); }
private void processFolder(string folderName, string[] foldersToSkip) { CSharp lang = new CSharp(); var fileEntries = System.IO.Directory.EnumerateFiles(folderName) .Where(fn => System.IO.Path.GetExtension(fn) == ".cs"); foreach (var fileEntry in fileEntries) { Trace.TraceInformation("Parsing file: " + fileEntry); lang.Parse(System.IO.File.ReadAllText(fileEntry), fileEntry); } var dirEntries = System.IO.Directory.EnumerateDirectories(folderName) .Where(fn => false == fn.Contains(".git")) .Where(fn => false == foldersToSkip.Contains(fn)); foreach (var dirEntry in dirEntries) { processFolder(dirEntry, foldersToSkip); } }
private static SyntaxNode Program(RParser.ProgContext prog, Func <ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var statements = new List <StatementSyntax>(); var inner = new Scope(scope); inner.InitR(); var pre = inner.PreStatements(); foreach (var expr in prog.expr_or_assign()) { pre.Clear(); var statement = transform(expr, inner) as StatementSyntax; Debug.Assert(statement != null); statements.AddRange(pre); statements.Add(statement); } return(CSharp.Block(statements)); }
private static MethodDeclarationSyntax singletonPublicSignal(MethodDeclarationSyntax method, out MethodDeclarationSyntax result) { result = method.WithIdentifier(CSharp.ParseToken("__" + method.Identifier.ToString())); var sCall = method.ReturnType.ToString() == "void" ? Templates.SingletonCall .Get <StatementSyntax>(result.Identifier.ToString()) : Templates.SingletonReturnCall .Get <StatementSyntax>(result.Identifier.ToString()); return(method .AddModifiers([email protected]()) .WithBody(CSharp.Block(sCall .ReplaceNodes(sCall .DescendantNodes() .OfType <ArgumentListSyntax>(), (on, nn) => nn.WithArguments(CSharp.SeparatedList(method .ParameterList .Parameters .Select(parameter => CSharp.Argument(CSharp.IdentifierName(parameter.Identifier))))))))); }
static RExtension() { _binaryOperators["+"] = CSharp.ParseExpression("RR.add"); _binaryOperators["-"] = CSharp.ParseExpression("RR.sub"); _binaryOperators["*"] = CSharp.ParseExpression("RR.mul"); _binaryOperators["/"] = CSharp.ParseExpression("RR.div"); _binaryOperators[">"] = CSharp.ParseExpression("RR.gt"); _binaryOperators[">="] = CSharp.ParseExpression("RR.ge"); _binaryOperators["<"] = CSharp.ParseExpression("RR.lt"); _binaryOperators["<="] = CSharp.ParseExpression("RR.le"); _binaryOperators["=="] = CSharp.ParseExpression("RR.eq"); _binaryOperators["!="] = CSharp.ParseExpression("RR.neq"); _binaryOperators["&&"] = CSharp.ParseExpression("RR.and"); _binaryOperators["&"] = CSharp.ParseExpression("RR.bnd"); _binaryOperators["||"] = CSharp.ParseExpression("RR.or"); _binaryOperators["|"] = CSharp.ParseExpression("RR.bor"); _unaryOperators["+"] = CSharp.ParseExpression("RR.ps"); _unaryOperators["-"] = CSharp.ParseExpression("RR.ns"); _unaryOperators["!"] = CSharp.ParseExpression("RR.neg"); }
private static ExpressionSyntax Call(ParserRuleContext node) { if (node.ChildCount == 1) { return(Expression(node.GetRuleContext <ParserRuleContext>(0))); } var expr = visitNode(node.GetRuleContext <ParserRuleContext>(0)); var args = null as ArgumentListSyntax; if (node.ChildCount == 4) { args = Arguments(node.GetRuleContext <ParserRuleContext>(2)); } else { args = CSharp.ArgumentList(); } return(CSharp.InvocationExpression(expr, args)); }
private StatementSyntax LinkThisInvocation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure) { Debug.Assert(invocation.Expression is IdentifierNameSyntax); //internal calls StatementSyntax result; if (syntaxOperation(invocation, success, failure, out result)) { return(result); } else { var identifier = (invocation.Expression as IdentifierNameSyntax) .ToString(); Signal signal = _class.GetSignal(identifier); if (signal != null) { var expr = invocation .WithExpression(CSharp.IdentifierName("__concurrent" + identifier)) .WithArgumentList(invocation .ArgumentList .AddArguments( CSharp.Argument( Templates.CancelationArgument), CSharp.Argument(WrapInLambda(success) .AddParameterListParameters(CSharp.Parameter(CSharp.ParseToken( "__res")))), CSharp.Argument(WrapInLambda(failure) .AddParameterListParameters(CSharp.Parameter(CSharp.ParseToken( "__ex")))))); return(CSharp.ExpressionStatement(Templates .Advance .Get <ExpressionSyntax>(expr))); } return(CSharp.ExpressionStatement(invocation)); } }
private static TypeDeclarationSyntax ParseModel(ClassDeclarationSyntax @class, ParameterListSyntax parameters, Scope scope) { var init = new List <ParameterSyntax>(); var props = new List <PropertyDeclarationSyntax>(); foreach (var member in @class.Members) { var field = ParseField(member); if (field == null) { continue; //error has already been registered } var type = field.Declaration.Type; var variable = field.Declaration .Variables .Single(); init.Add(CSharp.Parameter(variable.Identifier) .WithType(type) .WithDefault(CSharp.EqualsValueClause( variable.Initializer != null ? variable.Initializer.Value : CSharp.DefaultExpression(type)))); props.Add(ModelProperty.Get <PropertyDeclarationSyntax>(type) .WithIdentifier(variable.Identifier)); } if (!RoslynCompiler.HasVisibilityModifier(@class.Modifiers)) { @class = @class.AddModifiers(CSharp.Token(SyntaxKind.PublicKeyword)); } return(@class .WithMembers(CSharp.List <MemberDeclarationSyntax>( props.Union(new[] { GenerateConstructor(@class, init) })))); }
private static MethodDeclarationSyntax CompileAppMain(MethodDeclarationSyntax main, Options options) { foreach (var parameter in main.ParameterList.Parameters) { if (parameter.Default != null) { switch (parameter.Identifier.ToString()) { case "threads": var value = parameter ?.Default .Value; Debug.Assert(value != null); //td: error options.ThreadCount = int.Parse(value.ToString()); break; } } } return(main.WithParameterList(CSharp.ParameterList())); }
private StatementSyntax LinkExternalInvocation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure) { var queueStatement = null as StatementSyntax; if (_class.isQueueInvocation(invocation, true, success, out queueStatement)) { return(queueStatement); } Debug.Assert(invocation.Expression is MemberAccessExpressionSyntax); Debug.Assert(!invocation.Expression .DescendantNodes() .OfType <InvocationExpressionSyntax>() .Any()); //td: errors var symbol = _model.GetSymbolInfo(invocation.Expression).Symbol; if (symbol == null) { return(CSharp.ExpressionStatement(invocation)); } if (isConcurrent(symbol)) { return(CSharp.ExpressionStatement( invocation .WithArgumentList(invocation .ArgumentList .AddArguments( CSharp.Argument(Templates .SuccessFunction .Get <ExpressionSyntax>(success)), CSharp.Argument(Templates .FailureFunction .Get <ExpressionSyntax>(failure)))))); } return(CSharp.ExpressionStatement(invocation)); }
private SyntaxNode LinkTryStatements(List <StatementSyntax> statements, string variable) { var newStatements = new List <StatementSyntax>(); var firstTry = _trysInStack == 1; if (firstTry) { foreach (var v in _tryVariables) { newStatements.Add(Templates .TryVariable .Get <StatementSyntax>(v)); } _tryConcurrent = false; _tryVariables.Clear(); } return(CSharp.Block( newStatements.Union( CreateTrySplit(statements, 0, variable)))); }
private static StatementSyntax ParseConnection( IEnumerable<SyntaxToken> arguments, Scope scope, out IdentifierNameSyntax identifier, out bool resolved) { var id = scope.GetUniqueId("__connection"); identifier = CSharp.IdentifierName(id); resolved = false; if (arguments != null) { var service = scope.GetService<SyntaxToken, SyntaxNode, SemanticModel>(); var argumentList = (ArgumentListSyntax)service.ParseArgumentListFromTokens(arguments); var expr = default(ExpressionSyntax); foreach (var argument in argumentList.Arguments) { if (argument.NameColon != null && !argument.NameColon.IsMissing) { throw new NotImplementedException(); //td: connection related parameters } else if (expr == null) expr = argument.Expression; else { Debug.Assert(false); //td: error, too many parameters } } if (expr != null) { //assume the single parameter to be an already-constructed connection resolved = true; return AssignConnectionVariable.Get<StatementSyntax>(id, expr); } } return null; }
public void SyntacticalMatching_Usage() { RoslynCompiler compiler = new RoslynCompiler(); var syntax = compiler.Syntax(); //simple match syntax .match <ClassDeclarationSyntax>(c => !c.Members.OfType <ConstructorDeclarationSyntax>().Any()) .then(addConstructor); var tree = compiler.ApplySyntacticalPass("class foo { } class bar { bar() {} }"); Assert.IsTrue(tree .GetRoot() .DescendantNodes() .OfType <ConstructorDeclarationSyntax>() .Count() == 2); //must have added a constructor to "foo" //scope match & transform syntax .match <ClassDeclarationSyntax>(c => c.Identifier.ToString() == "foo") .descendants <MethodDeclarationSyntax>(named: "methods") .descendants <PropertyDeclarationSyntax>(prop => prop.Identifier.ToString().StartsWith("my"), named: "myProps") .then(syntax.transform() .replace("methods", method => ((MethodDeclarationSyntax)method) .WithIdentifier(CSharp.ParseToken("my" + ((MethodDeclarationSyntax)method).Identifier.ToString()))) .remove("myProps")); var scopeTree = compiler.ApplySyntacticalPass("class foo { public void Method() {} int myProp {get; set;} }"); Assert.IsTrue(scopeTree.ToString() == "class foo { public void myMethod() {} foo (){}}"); Assert.IsTrue(scopeTree .GetRoot() .DescendantNodes() .OfType <ConstructorDeclarationSyntax>() .Count() == 1); //must have added a constructor to "foo", since the syntax is the same }
static void Main(string [] args) { var method = GetProgramMethod("Main"); var cfg = ControlFlowGraph.Create(method); FormatControlFlowGraph(Console.Out, cfg); Console.WriteLine("--------------------"); var store = AnnotationStore.CreateStore(cfg, BlockOptimization.Detailed); PrintAnnotations(method, store); var language = CSharp.GetLanguage(CSharpVersion.V1); var body = method.Body.Decompile(language); var writer = language.GetWriter(new PlainTextFormatter(Console.Out)); writer.Write(method); }
private static Func <SyntaxNode, Scope, SyntaxNode> ProcessCodeFunction(IdentifierNameSyntax name, BlockSyntax body) { return((node, scope) => { LocalDeclarationStatementSyntax localDeclaration = (LocalDeclarationStatementSyntax)CSharp.ParseStatement("var id = () => {}"); var variable = localDeclaration.Declaration.Variables[0]; var lambda = variable.Initializer.Value as ParenthesizedLambdaExpressionSyntax; Debug.Assert(lambda != null); return localDeclaration .WithDeclaration(localDeclaration .Declaration .WithVariables(CSharp.SeparatedList(new[] { variable .WithIdentifier(name.Identifier) .WithInitializer(variable.Initializer .WithValue(lambda //.WithParameterList(invocation.ArgumentList) //td: extension arguments .WithBody(body))) }))); }); }
public SpearToolsManager(string gameName) { log = Log4NetLogger.getInstance(LogAppender.APP_CORE, Consts.DIR_SETTINGS); CSharp.setLogger(Log4NetLogger.getInstance(LogAppender.APP_CORE, Consts.DIR_SETTINGS)); this.theGame = gameName; SPConfig config = SPConfig.loadConfig(); if (config != null) { log.Debug("-- config.selectSettings() game:" + gameName); this.settings = config.settings; this.gameSettings = config.selectGame(gameName); this.paths = new PathsHelper(this.settings, this.gameSettings); } else { log.Warn("COULD NOT LOAD CONFIGURATION FILE"); this.settings = null; this.gameSettings = null; this.paths = null; } }
public async Task RemoveAsync_AfterInserting3Languages_AndRemoving1_2ShouldBeInTable() { // arrange var repo = await SetupAsync(); var toBeRemoved = new CSharp(); var langs = new[] { toBeRemoved, new CSharp(), new CSharp() }; await repo.InsertAllAsync(langs); // act var removedCount = await repo.RemoveAsync(toBeRemoved); // assert var count = await repo.Connection.Table <Language>().CountAsync(); count.ShouldBe(2); removedCount.ShouldBe(1); var itemsInTable = await repo.Connection.Table <Language>().ToListAsync(); itemsInTable.ShouldNotContain(toBeRemoved); }
public void CSharpComposerExtraNamespace() { testSnippet = "<%=5+5%>lol<%for (int i = 0; i < 5; i++) %>*" + "<%var blah = new List<int>();%>"; string[] namespaces = { "System.Collections.Generic" }; expectedCode = "using System.IO;\n\n" + "using System.Collections.Generic;\n" + "class CSharpTemplate\n{\n" + "public static TextWriter method(string json)\n{\n" + "StringWriter output = new StringWriter();\n" + "output.Write((5+5).ToString());\n" + "output.Write(\"lol\");\n" + "for (int i = 0; i < 5; i++) output.Write(\"*\");\n" + "var blah = new List<int>();" + "return output;\n}\n}"; chunks = new Parser(testSnippet).Parse(); var lang = new CSharp(); lang.AddExtras(null, namespaces, null); actualCode = lang.ComposeCode(chunks); Assert.AreEqual(expectedCode, actualCode); }
private ExpressionSyntax CreateCallback(bool success, bool leftOfParent, SyntaxToken token) { var arg1 = leftOfParent ? success ? Roslyn.@true : Roslyn.@false : Roslyn.@null; var arg2 = leftOfParent ? Roslyn.@null : success ? Roslyn.@true : Roslyn.@false; var ex = success ? Roslyn.@null : Templates.FailureParameter; return(CSharp .InvocationExpression(CSharp.IdentifierName(token)) .WithArgumentList(CSharp.ArgumentList(CSharp.SeparatedList(new[] { CSharp.Argument(arg1), CSharp.Argument(arg2), CSharp.Argument(ex) })))); }
//type code extensions private Func <ClassDeclarationSyntax, ParameterListSyntax, BlockSyntax, Scope, TypeDeclarationSyntax> TypeCodeExtensions_Transform( bool expectsIdentifier, bool expectsParameters) { return((@class, parameters, code, scope) => { var hasIdentifier = @class.Identifier.ToString().Equals("SomeIdentifier"); if (expectsIdentifier) { Assert.IsTrue(hasIdentifier); } if (expectsParameters) { Assert.IsNotNull(parameters); } if (!hasIdentifier) { @class = @class.WithIdentifier(CSharp .ParseToken("SomeIdentifier")); } if (parameters != null) { @class = @class.AddMembers(CSharp .MethodDeclaration(RoslynCompiler.@void, "SomeParameters") .AddParameterListParameters(parameters .Parameters .ToArray())); } return @class .AddMembers(CSharp .MethodDeclaration(RoslynCompiler.@void, "SomeMethod") .WithBody(code)); }); }
//member extensions private static Func <SyntaxNode, Scope, LexicalExtension <SyntaxToken>, SyntaxNode> TransformMember( Func <MethodDeclarationSyntax, Scope, MemberDeclarationSyntax> transform) { return((node, scope, extension) => { var method = node as MethodDeclarationSyntax; if (method == null) { Debug.Assert(false); //td: error return node; } if (node.Parent is TypeDeclarationSyntax) { var service = scope.GetService <SyntaxToken, SyntaxNode, SemanticModel>(); var body = (BlockSyntax)service.ParseCodeFromTokens(extension.Body); var identifier = extension.Identifier.IsKind(SyntaxKind.None) ? CSharp.Identifier("__") : extension.Identifier; var parameters = default(ParameterListSyntax); if (extension.Arguments != null && extension.Arguments.Any()) { parameters = (ParameterListSyntax)service.ParseParamListFromTokens(extension.Arguments); method = method.WithParameterList(parameters); } return transform(method .WithIdentifier(identifier) .WithReturnType(CSharp.ParseTypeName(extension.Keyword.ToString())) .WithBody(body), scope); } Debug.Assert(false); //td: error return node; }); }
//type extensions private static Func <SyntaxNode, Scope, LexicalExtension <SyntaxToken>, SyntaxNode> TransformType( Func <ClassDeclarationSyntax, ParameterListSyntax, Scope, TypeDeclarationSyntax> transform) { return((node, scope, extension) => { var @class = node as ClassDeclarationSyntax; if (@class == null) { Debug.Assert(false); //td: error return node; } if (node.Parent is NamespaceDeclarationSyntax || node.Parent is CompilationUnitSyntax) { var service = scope.GetService <SyntaxToken, SyntaxNode, SemanticModel>(); var members = (service .ParseMembersFromTokens(extension.Body) as ClassDeclarationSyntax) .Members; var identifier = extension.Identifier.IsKind(SyntaxKind.None) ? CSharp.Identifier("__") : extension.Identifier; var parameters = default(ParameterListSyntax); if (extension.Arguments != null && extension.Arguments.Any()) { parameters = (ParameterListSyntax)service.ParseParamListFromTokens(extension.Arguments); } return transform(@class .WithIdentifier(identifier) .WithMembers(members), parameters, scope); } Debug.Assert(false); //td: error return node; }); }
private static BlockStatement DecompileStateMachine(this MethodBody body, MethodSpecificContext enclosingMethodContext, IStateMachineRemoverStep removeStateMachineStep, Func <DecompilationContext, IStateMachineData> stateMachineDataSelector, out DecompilationContext decompilationContext) { ILanguage language = CSharp.GetLanguage(CSharpVersion.V4); removeStateMachineStep.Language = language; DecompilationPipeline thePipeline = GetStateMachineRemovalPipeline(removeStateMachineStep, stateMachineDataSelector); decompilationContext = thePipeline.Run(body, language); enclosingMethodContext.Variables.AddRange(decompilationContext.MethodContext.Variables); enclosingMethodContext.VariableDefinitionToNameMap.AddRange(decompilationContext.MethodContext.VariableDefinitionToNameMap); enclosingMethodContext.AddInnerMethodParametersToContext(decompilationContext.MethodContext); enclosingMethodContext.VariableAssignmentData.AddRange(decompilationContext.MethodContext.VariableAssignmentData); enclosingMethodContext.GotoLabels.AddRange(decompilationContext.MethodContext.GotoLabels); enclosingMethodContext.GotoStatements.AddRange(decompilationContext.MethodContext.GotoStatements); BlockStatement theBlockStatement = thePipeline.Body; return(theBlockStatement); }
private SyntaxNode myExtSyntactical(SyntaxNode node, Scope scope, LexicalExtension <SyntaxToken> extension) { Assert.IsTrue(node is MethodDeclarationSyntax); var method = node as MethodDeclarationSyntax; Assert.IsTrue(method.Identifier.ToString() == "__extension"); var argString = RoslynCompiler.TokensToString(extension.Arguments); Assert.IsTrue(argString == "(int i) "); var arguments = CSharp.ParseParameterList(argString); var codeString = RoslynCompiler.TokensToString(extension.Body); var codeNode = CSharp.ParseStatement(codeString); Assert.IsTrue(codeNode is BlockSyntax); var code = codeNode as BlockSyntax; return(method .WithIdentifier(CSharp.ParseToken("my_ext_s")) .WithParameterList(arguments) .WithBody(code)); }
public static string Generate(IEnumerable <TypeMeta> items, bool writable, string targetNamespace, GenerationType gt) { if (items == null || items.Count() < 1) { MessageBox.Show("No items imported"); return(null); } switch (gt) { case GenerationType.FSharpRecord: return(MapItems(items, x => FSharp.generateRecord(writable, x))); case GenerationType.CSharpClass: return(MapItems(items, x => CSharp.generateClass(writable, x))); case GenerationType.CSharpFile: return(MapItems(items, x => CSharp.generateClassFile(targetNamespace, writable, x))); default: MessageBox.Show("Not implemented"); return(null); } }
public static bool Train(string currentDirectory, string searchPattern, Func <bool> IsTerminated) { currentDirectory = @"D:\Mozart\src\"; var lex = new CSharp(); string outputFileName = @"D:\Mozart\Mozart.cbow"; Matrix <Word> Model = null; if (File.Exists(outputFileName)) { Model = LoadFromFile(outputFileName, SIZE, out string fmt, out int dims); } else { Model = BuildFromPlainText(currentDirectory, "*.cs", lex, outputFileName); } TrainMikolovModel(MakeFileList(new string[] { currentDirectory }, "*.cs", SearchOption.AllDirectories), lex, Model, (loss) => { }, IsTerminated); CBOW.SaveToFile( Matrix <Word> .Sort(Model), "CBOW", CBOW.DIMS, outputFileName); return(false); }
private IEnumerable <StatementSyntax> CreateTrySplit(List <StatementSyntax> statements, int index, string variable) { bool foundTry = false; for (int i = index; i < statements.Count; i++, index++) { if (foundTry) { yield return(CSharp.IfStatement( Templates.Negation.Get <ExpressionSyntax>(CSharp.IdentifierName(variable)), CSharp.Block(CreateTrySplit(statements, index, variable)))); yield break; } var statement = statements[i]; if (statement is TryStatementSyntax) { foundTry = true; var @try = statement as TryStatementSyntax; yield return(@try .WithCatches(CSharp.List( @try .Catches .Select(c => c.WithBlock(CSharp.Block(new [] { Templates .SetTryVariable .Get <StatementSyntax>(variable) }.Union( c.Block.Statements))))))); } else { yield return(statement); } } }
public void DelegatesAndExternTest() { CSharp lang = new CSharp(); CodeFile cf = lang.Parse(System.IO.File.ReadAllText(@".\Programs\CSharp\DelegatesAndExterns.txt"), @".\Programs\CSharp\DelegatesAndExterns.txt"); var functionsAndDelegates = cf.Children.First().Children.First().Children; Assert.AreEqual(3, functionsAndDelegates.Count()); //top level functions. var del1 = (functionsAndDelegates.First() as FunctionDefinition); Assert.IsTrue(del1.TypeOfFunction == FunctionTypes.Delegate); Assert.AreEqual("GetNative", del1.Name); Assert.AreEqual(1, del1.Parameters.Count()); Assert.AreEqual(AccessSpecifiers.Private, del1.AccessSpecifiers); var fn1 = functionsAndDelegates.Skip(1).First() as FunctionDefinition; Assert.AreEqual(FunctionTypes.MemberFunction, fn1.TypeOfFunction); var childDel1 = fn1.Children.First() as FunctionDefinition; Assert.AreEqual(childDel1.TypeOfFunction, FunctionTypes.AnonymousDelegate); Assert.AreEqual(0, childDel1.Parameters.Count()); var childDel2 = fn1.Children.Skip(1).First() as FunctionDefinition; Assert.AreEqual(childDel2.TypeOfFunction, FunctionTypes.AnonymousDelegate); Assert.AreEqual(1, childDel2.Parameters.Count()); var fn2 = functionsAndDelegates.Skip(2).First() as FunctionDefinition; Assert.AreEqual(FunctionTypes.External, fn2.TypeOfFunction); Assert.IsTrue(fn2.IsExtern); Assert.IsTrue((fn2.StorageSpecifiers & StorageSpecifiers.Extern) > 0); Assert.IsTrue((fn2.StorageSpecifiers & StorageSpecifiers.Static) > 0); Assert.AreEqual(3, fn2.Parameters.Count()); }
private static ExpressionSyntax ParseBody(IEnumerable<SyntaxToken> body, Scope scope, out AnonymousObjectCreationExpressionSyntax parameters) { parameters = null; var builder = new StringBuilder(); var @params = new List<AnonymousObjectMemberDeclaratorSyntax>(); builder.Append("@\""); foreach (var token in body) { var str = token.ToFullString(); if (token.IsKind(SyntaxKind.IdentifierToken) && str.StartsWith("@")) { var newToken = CSharp.ParseToken(str.Substring(1)) .WithAdditionalAnnotations(token.GetAnnotations()); @params.Add(CSharp.AnonymousObjectMemberDeclarator( CSharp.NameEquals(CSharp.IdentifierName(newToken)), CSharp.IdentifierName(newToken))); } builder.Append(str); } builder.Append("\""); var result = CSharp.ParseExpression(builder.ToString()); if (result == null) { Debug.Assert(false); //td: error return null; } parameters = CSharp.AnonymousObjectCreationExpression(CSharp.SeparatedList( @params)); return result; }
public void GetContextBlockTest() { Trace.Listeners.Add(new ConsoleTraceListener()); CSharp csharp = new CSharp(); CodeFile cf = csharp.Parse(System.IO.File.ReadAllText(@".\Programs\CSharp\Blocks.txt"), @".\Programs\CSharp\Blocks.txt"); var list = cf.GetContextAtLine(30).ToList(); Assert.AreEqual(list.Count, 9); Assert.AreEqual(list[0].Kind, SyntaxEntityKind.Else); Assert.AreEqual(list[1].Kind, SyntaxEntityKind.If); Assert.AreEqual(list[2].Kind, SyntaxEntityKind.For); Assert.AreEqual(list[3].Kind, SyntaxEntityKind.Try); Assert.AreEqual(list[4].Kind, SyntaxEntityKind.Function); Assert.AreEqual(list[5].Kind, SyntaxEntityKind.Class); Assert.AreEqual(list[6].Kind, SyntaxEntityKind.Class); Assert.AreEqual(list[7].Kind, SyntaxEntityKind.Namespace); Assert.AreEqual(list[8].Kind, SyntaxEntityKind.CodeFile); Assert.AreEqual(list[4].Name, "Foo"); Assert.AreEqual(list[5].Name, "InnerClass"); Assert.AreEqual(list[6].Name, "OuterClass"); Assert.AreEqual(list[7].Name, "Microsoft.CodeTalk.LanguageService.Tests.Programs"); }
private static bool IsInsideInterpolation(CSharp.CSharpSyntaxNode oldTree, int start) { var token = oldTree.FindToken(start, findInsideTrivia: false); for (var parent = token.Parent; // for each parent parent != null; parent = parent.Parent) { if (parent.Kind() == SyntaxKind.InterpolatedStringExpression) { return true; } } return false; }
/// <summary> /// Affected range of a change is the range within which nodes can be affected by a change /// and cannot be reused. Because of lookahead effective range of a change is larger than /// the change itself. /// </summary> private static TextChangeRange ExtendToAffectedRange( CSharp.CSharpSyntaxNode oldTree, TextChangeRange changeRange) { // we will increase affected range of the change by the number of lookahead tokens // original code in Blender seem to imply the lookahead at the end of a node is 1 token // max. TODO: 1 token lookahead seems a bit too optimistic. Increase if needed. const int maxLookahead = 1; // check if change is not after the end. TODO: there should be an assert somwhere about // changes starting at least at the End of old tree var lastCharIndex = oldTree.FullWidth - 1; // Move the start of the change range so that it is contained within oldTree. var start = Math.Max(Math.Min(changeRange.Span.Start, lastCharIndex), 0); // the first iteration aligns us with the change start. subsequent iteration move us to // the left by maxLookahead tokens. We only need to do this as long as we're not at the // start of the tree. Also, the tokens we get back may be zero width. In that case we // need to keep on looking backward. for (var i = 0; start > 0 && i <= maxLookahead;) { var token = oldTree.FindToken(start, findInsideTrivia: false); Debug.Assert(token.Kind() != SyntaxKind.None, "how could we not get a real token back?"); start = Math.Max(0, token.Position - 1); // Only increment i if we got a non-zero width token. Otherwise, we want to just do // this again having moved back one space. if (token.FullWidth > 0) { i++; } } if (IsInsideInterpolation(oldTree, start)) { // If the changed range starts inside an interpolated string, we // move the start of the change range to the beginning of the line so that any // interpolated string literal in the changed range will be scanned in its entirety. var column = oldTree.SyntaxTree.GetLineSpan(new TextSpan(start, 0)).Span.Start.Character; start = Math.Max(start - column, 0); } var finalSpan = TextSpan.FromBounds(start, changeRange.Span.End); var finalLength = changeRange.NewLength + (changeRange.Span.Start - start); return new TextChangeRange(finalSpan, finalLength); }
/// <summary> /// Returns the name of a given AstType /// </summary> /// <param name="type"></param> /// <returns>The name</returns> public static string GetTypeName(CSharp.AstType type) { if (type is CSharp.SimpleType) return (type as CSharp.SimpleType).Identifier; else if (type == CSharp.AstType.Null) return String.Empty; else if (type is CSharp.PrimitiveType) return (type as CSharp.PrimitiveType).Keyword; else if (type is CSharp.ComposedType) { CSharp.ComposedType ct = type as CSharp.ComposedType; return GetTypeName(ct.BaseType); } else { return type.ToString(); } }
public static TypeDefinition ResolveMemberType(CSharp.MemberReferenceExpression mref) { foreach (var ann in mref.Annotations) { if (ann is ICSharpCode.Decompiler.Ast.TypeInformation) { ICSharpCode.Decompiler.Ast.TypeInformation typeAn = ann as ICSharpCode.Decompiler.Ast.TypeInformation; if (typeAn.InferredType != null) { return typeAn.InferredType.Resolve(); } } } return null; }
/// <summary> /// Returns if a method is marked as an external method or not /// </summary> /// <param name="method"></param> /// <returns>True if is external</returns> public static bool IsDLLImportMethod(CSharp.MethodDeclaration method) { foreach (CSharp.AttributeSection section in method.Attributes) { foreach (CSharp.Attribute t in section.Attributes) { if (Resolver.GetTypeName(t.Type).Equals("DllImport")) { return true; } } } return false; }
/// <summary> /// Checks if the node is child of other node of the specified type /// </summary> /// <param name="member">Node</param> /// <param name="type">Type of the parent node</param> /// <returns>Bool indicating if is child or not</returns> public static bool IsChildOf(CSharp.AstNode member, Type type) { CSharp.AstNode m = member as CSharp.AstNode; while (m.Parent != null) { if (m.Parent.GetType() == type) { return true; } m = m.Parent; } return false; }
protected CSharp.CSharpCompilation CreateCSharpCompilation( string code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, string assemblyName = null, IEnumerable<MetadataReference> referencedAssemblies = null) { return CreateCSharpCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null); }
/// <summary> /// Returns the childs nodes of type specified by variable type /// </summary> /// <param name="member">Original node</param> /// <param name="type">Target type of</param> /// <returns>The resulting node</returns> public static List<CSharp.AstNode> GetChildrenOf(CSharp.AstNode member, Type type) { List<CSharp.AstNode> result = new List<CSharp.AstNode>(); CSharp.AstNode m = member as CSharp.AstNode; foreach (CSharp.AstNode n in m.Children) { if (n.GetType() == type) { result.Add(n); } result.AddRange(GetChildrenOf(n, type)); } return result; }
/// <summary> /// Returns if the node has a child of a specified type /// </summary> /// <param name="member">Original node</param> /// <param name="type">Target type of</param> /// <returns>The resulting node</returns> public static bool HasChildOf(CSharp.AstNode member, Type type) { CSharp.AstNode m = member as CSharp.AstNode; foreach (CSharp.AstNode n in m.Children) { if (n.GetType() == type) { return true; } bool tmp = HasChildOf(n, type); if (tmp) return true; } return false; }
/// <summary> /// Gets the library in which the external method is located /// </summary> /// <param name="attributes"></param> /// <returns>The library name</returns> public static string GetLibraryFromDllImport(CSharp.AstNodeCollection<CSharp.AttributeSection> attributes) { foreach (CSharp.AttributeSection section in attributes) { foreach (CSharp.Attribute t in section.Attributes) { if (Resolver.GetTypeName(t.Type).Equals("DllImport")) { foreach (CSharp.Expression e in t.Arguments) { if (e is CSharp.PrimitiveExpression) { return (e as CSharp.PrimitiveExpression).Value as string; } } } } } return String.Empty; }
/// <summary> /// Returns the name of the target external function /// </summary> /// <param name="attributes"></param> /// <returns>The real name of the external function in the library</returns> public static string GetEntryPointFromDllImport(CSharp.AstNodeCollection<CSharp.AttributeSection> attributes) { foreach (CSharp.AttributeSection section in attributes) { foreach (CSharp.Attribute t in section.Attributes) { if (Resolver.GetTypeName(t.Type).Equals("DllImport")) { foreach (CSharp.Expression e in t.Arguments) { if (e is CSharp.AssignmentExpression) { CSharp.AssignmentExpression assign = e as CSharp.AssignmentExpression; if (assign.Left is CSharp.IdentifierExpression) { if ((assign.Left as CSharp.IdentifierExpression).Identifier.Equals("EntryPoint")) { return (assign.Right as CSharp.PrimitiveExpression).Value.ToString(); } } } } } } } return String.Empty; }
public static string InferNamespace(CSharp.AstType type) { if (type.Annotations.Any()) { foreach (Object obj in type.Annotations) { if (obj is TypeDefinition) { var typeDef = obj as TypeDefinition; return typeDef.Namespace; } else if (obj is MemberReference) { var member = obj as MemberReference; return member.FullName.Substring(0, member.FullName.Length - member.FullName.LastIndexOf('.') - 1); } } } return String.Empty; }
internal BlendedNode(CSharp.CSharpSyntaxNode node, SyntaxToken token, Blender blender) { this.Node = node; this.Token = token; this.Blender = blender; }
protected CSharp.CSharpCompilation CreateCSharpCompilation( string assemblyName, string code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, IEnumerable<MetadataReference> referencedAssemblies = null, IEnumerable<Compilation> referencedCompilations = null) { if (assemblyName == null) { assemblyName = GetUniqueName(); } if (parseOptions == null) { parseOptions = CSharp.CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None); } if (compilationOptions == null) { compilationOptions = new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); } var references = new List<MetadataReference>(); if (referencedAssemblies == null) { references.Add(MscorlibRef); references.Add(SystemRef); references.Add(SystemCoreRef); //TODO: references.Add(MsCSRef); references.Add(SystemXmlRef); references.Add(SystemXmlLinqRef); } else { references.AddRange(referencedAssemblies); } AddReferencedCompilations(referencedCompilations, references); var tree = CSharp.SyntaxFactory.ParseSyntaxTree(code, options: parseOptions); return CSharp.CSharpCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions); }
/// <summary> /// Returns if the specified type name is a delegate type /// </summary> /// <param name="type">Identifier</param> /// <returns>True/False</returns> public static bool IsDelegateType(CSharp.AstType type) { return IsDelegateType(Resolver.GetTypeName(type)); }
/// <summary> /// Checks if the node is direct child of other node of the specified type /// </summary> /// <param name="member">Node</param> /// <param name="type">Type of the parent node</param> /// <returns>Bool indicating if is child or not</returns> public static bool IsDirectChildOf(CSharp.AstNode member, Type type) { if (member == null) return false; if (member.Parent == null) return false; return member.Parent.GetType() == type; }
/// <summary> /// Returns if a method is marked as synchronized or not /// </summary> /// <param name="method"></param> /// <returns>True if synchronized</returns> public static bool IsSynchronizedMethod(CSharp.MethodDeclaration method) { foreach (CSharp.AttributeSection section in method.Attributes) { foreach (CSharp.Attribute t in section.Attributes) { if (Resolver.GetTypeName(t.Type).Equals("MethodImpl")) { foreach (CSharp.Expression e in t.Arguments) { if (e is CSharp.MemberReferenceExpression) { if ((e as CSharp.MemberReferenceExpression).MemberName == "Synchronized") { return true; } } } } } } return false; }
/// <summary> /// Returns if a type has template arguments /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsTemplatizedType(CSharp.AstType type) { if (type is CSharp.SimpleType) { CSharp.SimpleType t = type as CSharp.SimpleType; return t.TypeArguments.Any(); } else { if (HasChildOf(type, typeof(CSharp.SimpleType))) { bool aux = false; foreach (var node in GetChildrenOf(type, typeof(CSharp.SimpleType))) { if (IsTemplatizedType(type)) aux = true; } return aux; } return false; } }
/// <summary> /// Returns the first parent node of type specified by variable type /// </summary> /// <param name="member">Original node</param> /// <param name="type">Target type of</param> /// <returns>The resulting node</returns> public static CSharp.AstNode GetParentOf(CSharp.AstNode member, Type type) { CSharp.AstNode m = member as CSharp.AstNode; while (m.Parent != null) { if (m.Parent.GetType() == type) { return m.Parent; } m = m.Parent; } return CSharp.AstNode.Null; }