public static SyntaxNode Parse(CobaltParser parser) { if (parser.Match(TokenClass.IDENTIFIER, "if", TokenClass.OPEN_PARAN, "(")) { Statement ret = new Statement(); parser.Match(TokenClass.IDENTIFIER, TokenClass.OPEN_PARAN, typeof(Expression), TokenClass.CLOSE_PARAN, typeof(Statement)); return ret; } else if (parser.Match(TokenClass.IDENTIFIER, "while", TokenClass.OPEN_PARAN, "(")) { Statement ret = new Statement(); parser.Match(TokenClass.IDENTIFIER, TokenClass.OPEN_PARAN, typeof(Expression), TokenClass.CLOSE_PARAN, typeof(Statement)); return ret; } else if (parser.Match(TokenClass.IDENTIFIER, TokenClass.ASSIGN)) { Statement stn = new Statement(); parser.Term(stn, typeof(Identifier), TokenClass.ASSIGN, typeof(Expression), TokenClass.SEMI_COLON); return stn; } else if (parser.Match(TokenClass.OPEN_BRACKET)) { CodeBlock block = new CodeBlock(); parser.ReadToken(); while (parser.PeekToken() != null && parser.PeekToken().Class != TokenClass.CLOSE_BRACKET) block.AddLeave(Statement.Parse(parser)); parser.ReadToken(); return block; } return null; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { }
public override Expression Generate(object args, CodeBlock cb) { if (args == null) { return Ast.ReadField(null, Unspecified); } else { // discard effectfree List<Expression> newargs = new List<Expression>(); Expression[] aa = GetAstList(args as Cons, cb); if (aa.Length == 1) { return aa[0]; } for (int i = 0; i < aa.Length - 1; i++) { Expression a = aa[i]; Expression uwa = Unwrap(a); if (uwa is ConstantExpression) { continue; } if (uwa is MemberExpression) { MemberExpression me = uwa as MemberExpression; if (me.Member == Unspecified) { continue; } } if (uwa is CommaExpression) { newargs.AddRange(((CommaExpression)uwa).Expressions); } else { newargs.Add(a); } } if (newargs.Count == 0) { return aa[aa.Length - 1]; } else { Expression uwa = aa[aa.Length - 1]; if (uwa is CommaExpression) { newargs.AddRange(((CommaExpression)uwa).Expressions); } else { newargs.Add(uwa); } return Ast.Comma(newargs); } } }
//(import (ironscheme clr)) //(define f (ffi-callout int32 (void* uint16))) public override Expression Generate(object args, CodeBlock cb) { Cons c = args as Cons; Type returntype = GetFFIType(Unquote(c.car)); c = c.cdr as Cons; List<Type> paramtypes = new List<Type>(); while (c != null) { paramtypes.Add(GetFFIType(Unquote(c.car))); c = c.cdr as Cons; } CodeBlock outer = Ast.CodeBlock("outer"); outer.Parent = cb; Variable ptr = Variable.Parameter(outer, SymbolTable.StringToId("ptr"), typeof(object)); outer.AddParameter(ptr); CodeBlock inner = GenerateInvoke("ffi-callout", a => MakePointerCall(ptr, returntype, paramtypes, a), returntype, paramtypes, outer); outer.Body = Ast.Return(MakeClosure(inner, false)); return MakeClosure(outer, false); }
internal ScriptCode(CodeBlock code, LanguageContext languageContext, CompilerContext compilerContext) { Assert.NotNull(code, languageContext, compilerContext); _code = code; _languageContext = languageContext; _compilerContext = compilerContext; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { switch (property) { case DmlTokens.INTRINSIC_DIRECTION: ((DmlBullet)bullet.Value).Direction = (Vector2)(stack.Pop().Value); break; case DmlTokens.INTRINSIC_SPEED: ((DmlBullet)bullet.Value).Speed = (double)(stack.Pop().Value); break; case DmlTokens.INTRINSIC_COLOUR: ((DmlBullet)bullet.Value).Colour = (Color)(stack.Pop().Value); break; case DmlTokens.INTRINSIC_SPRITE: string name = (string)(stack.Pop().Value); ((DmlBullet)bullet.Value).SetSprite(name.Substring(1, name.Length - 2)); break; default: throw new DmlSyntaxError(String.Format("Unknown intrinsic property \"{0}\"", property)); } }
/// <summary> /// The clean code. /// </summary> /// <param name="code"> /// The code. /// </param> /// <returns> /// The System.String. /// </returns> public static string CleanCode(string code) { CodeBlock codeBlock = new CodeBlock(code); codeBlock.GetSnippets(); codeBlock.ReplaceSnippets(); return codeBlock.HighlightedText; }
public static void Times(this int value, CodeBlock codeBlock) { for (int i = 0; i < value; i++) { codeBlock(); } }
public CodeBlock GetCode() { CodeBlock block = new CodeBlock(); block.Code = GetCurrentInput(); return block; }
public override Expression Generate(object args, CodeBlock cb) { Cons c = (Cons)args; var an = c.car; if (an is Annotation) { var anno = (Annotation)an; if (anno.source is Cons) { Cons src = anno.source as Cons; string filename = src.car as string; object location = src.cdr; //LocationHint = filename; if (cb.Filename == null) { cb.Filename = filename; } if (location is string) { var SpanHint = ExtractLocation(location as string); return Apply(cb, c, SpanHint); } else if (location is SourceSpan) { return Apply(cb, c, (SourceSpan)location); } } } return GetAst(c.cdr, cb); }
static void Main(string[] args) { var root = XDocument.Load("frames.xml").Root; var FrameDescriptions = root.Elements("Frame").Select(XFrame => FrameDescription.GetFrameDescription(XFrame)); //var props = frame.Elements("Property").Select(XProperty => PropertyDescription.GetProperty(XProperty)).ToList(); //foreach (var p in props.Where(pp => pp != null)) // Console.WriteLine(p.PropertyDecoder.Text); var Code = new CodeBlock() { new CodeLine("using System;"), new CodeLine("using System.Collections.Generic;"), new CodeLine("using System.Linq;"), new CodeLine("using System.Text;"), new CodeLine(), new CodeHeaderedBlock("namespace BlokFrames") { FrameDescriptions.Select(fd => fd.GetCode()) } }; using (TextWriter tw = new StreamWriter("Frames.cs")) { tw.WriteLine(Code.Text); } Console.WriteLine(Code.Text); Console.Read(); }
public override Expression Generate(object args, CodeBlock c) { var refs = ClrGenerator.SaveReferences(); CodeBlock cb = Ast.CodeBlock(SpanHint, GetLambdaName(c)); NameHint = SymbolId.Empty; cb.Filename = LocationHint; cb.Parent = c; cb.Source = new Cons(SymbolTable.StringToObject("lambda"), args); object arg = Builtins.First(args); Cons body = Builtins.Cdr(args) as Cons; bool isrest = AssignParameters(cb, arg); cb.IsRest = isrest; List<Statement> stmts = new List<Statement>(); FillBody(cb, stmts, body, true); Expression ex = MakeClosure(cb, isrest); ClrGenerator.ResetReferences(refs); return ex; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { switch (property) { case DmlTokens.INTRINSIC_ORIGIN: stack.Push(new DmlObject(DmlType.Vector, ((DmlBullet)bullet.Value).Origin)); break; case DmlTokens.INTRINSIC_POSITION: stack.Push(new DmlObject(DmlType.Vector, ((DmlBullet)bullet.Value).Position)); break; case DmlTokens.INTRINSIC_DIRECTION: stack.Push(new DmlObject(DmlType.Vector, ((DmlBullet)bullet.Value).Direction)); break; case DmlTokens.INTRINSIC_SPEED: stack.Push(new DmlObject(DmlType.Vector, ((DmlBullet)bullet.Value).Speed)); break; case DmlTokens.INTRINSIC_COLOUR: stack.Push(new DmlObject(DmlType.Colour, ((DmlBullet)bullet.Value).Colour)); break; case DmlTokens.INTRINSIC_TIME: stack.Push(new DmlObject(DmlType.Number, ((DmlBullet)bullet.Value).LocalTime)); break; case DmlTokens.INTRINSIC_VELOCITY: DmlBullet b = (DmlBullet)bullet.Value; stack.Push(new DmlObject(DmlType.Vector, b.Direction * (float)b.Speed)); break; default: throw new DmlSyntaxError(String.Format("Unknown bullet property \"{0}\"", property)); } }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { ((DmlBullet)bullet.Value).Dead = true; }
public Value Else(Value previous, CodeBlock block) { if (previous.Type == ValueType.IfFalse) { return block.Execute(Interpreter); } return previous; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { bullet.BoundVars[name] = stack.Pop(); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { system.GlobalVars.Add(name, stack.Pop()); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { stack.Push(system.GlobalVars[name]); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { var paramNames = new string[paramCount]; var values = new DmlObject[paramCount]; DmlObject top; List<DmlObject> param; for (int i = 0; i < paramCount; i++) { top = stack.Pop(); param = (List<DmlObject>)top.Value; paramNames[i] = (string)(param[0].Value); values[i] = param[1]; } var currentAngle = 0d; if (hasAngleOffset) currentAngle = (double)(stack.Pop().Value); if (hasAngleOffsetD) currentAngle = Math.PI / 180 * (double)(stack.Pop().Value); var speed = (double)(stack.Pop().Value); var streams = (int)(double)(stack.Pop().Value); var factory = (DmlBulletFactory)(stack.Pop().Value); var oldBullet = (DmlBullet)(bullet.Value); var angleIncrement = 2*Math.PI/streams; DmlObject newBulletObj; DmlBullet newBullet; Vector2 direction; bool local = bullet != null; for (int i = 0; i < streams; i++) { newBulletObj = factory.Instantiate(oldBullet.Origin, system); newBullet = (DmlBullet)(newBulletObj.Value); direction = new Vector2((float)Math.Cos(currentAngle), (float)Math.Sin(currentAngle)); newBullet.Direction = direction; newBullet.Speed = speed; for (int j = 0; j < paramCount; j++) newBulletObj.SetVar(paramNames[j], values[j]); if (local) oldBullet.Children.Add(newBullet); system.AddBullet(newBullet); currentAngle += angleIncrement; } }
/// <summary> /// Provides an automated wrapper for timing an operation and logging a message to a given PerformanceLog /// </summary> /// <param name="message">The message to log.</param> /// <param name="log">The <typeparamref name="PerformanceLog"/> the message should be written to.</param> /// <param name="code">The code to be invoked and timed.</param> /// <returns><typeparamref name="PerformanceLog"/> which is the same <typeparamref name="PerformanceLog"/> passed into the method.</returns> public PerformanceLog LogScope(String message, PerformanceLog log, CodeBlock code) { lock (obj) { this.SetMarker(); code.Invoke(); this.ReleaseMarker(); log.LogData(message, this.Duration); } return log; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { var local = bullet != null; DmlBullet parent = null; Vector2 origin = Vector2.Zero; if (local) { parent = (DmlBullet)(bullet.Value); origin = parent.Position; } if (hasOrigin) origin = (Vector2)(stack.Pop().Value); double angleMin = 0, angleMax = 2 * Math.PI, speedMin, speedMax; if (hasAngleRange) { var angleRange = (List<DmlObject>)(stack.Pop().Value); angleMin = (double)angleRange[0].Value; angleMax = (double)angleRange[1].Value; if (degrees) { angleMin *= Math.PI / 180; angleMax *= Math.PI / 180; } } var speedRange = (List<DmlObject>)(stack.Pop().Value); speedMin = (double)speedRange[0].Value; speedMax = (double)speedRange[1].Value; var count = (double)(stack.Pop().Value); var factory = (DmlBulletFactory)(stack.Pop().Value); double crntAngle, crntSpeed; Vector2 direction; DmlObject newObj; DmlBullet newBullet; for (int i = 0; i < count; i++) { crntAngle = (angleMax - angleMin) * Globals.randGen.NextDouble() + angleMin; crntSpeed = (speedMax - speedMin) * Globals.randGen.NextDouble() + speedMin; direction = new Vector2((float)Math.Cos(crntAngle), (float)Math.Sin(crntAngle)); newObj = factory.Instantiate(origin, system); newBullet = (DmlBullet)(newObj.Value); newBullet.Direction = direction; newBullet.Speed = crntSpeed; if (local) parent.Children.Add(newBullet); system.AddBullet(newBullet); } }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { if (!(bool)(stack.Pop().Value)) block.currentPosition = position; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { var b = (DmlBullet)(bullet.Value); b.Direction = GeometryUtils.RotateVector(b.Direction, (double)(stack.Pop().Value), degrees: degrees); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { DmlObject second = stack.Pop(); DmlObject first = stack.Pop(); // Add the two objects together ya dingus! }
public override Expression Generate(object args, CodeBlock cb) { SymbolId s = (SymbolId)Builtins.First(args); assigns[s] = true; if (libraryglobals.ContainsKey(s)) { libraryglobals.Remove(s); } if (libraryglobalsN.ContainsKey(s)) { libraryglobalsN.Remove(s); } if (libraryglobalsX.ContainsKey(s)) { libraryglobalsX.Remove(s); } setstack.Push(s); NameHint = Builtins.UnGenSymInternal(s); var prevvh = VarHint; VarHint = s; Expression value = GetAst(Builtins.Second(args), cb); VarHint = prevvh; setstack.Pop(); NameHint = SymbolId.Invalid; Variable v = cb.Lookup(s); Statement r = null; if (v == null) { r = Ast.Statement(Ast.SimpleCallHelper(SetSymbolValue, Ast.Constant(s), value)); } else { //Trace.Assert(cb.Parent != null); value = Ast.ConvertHelper(value, v.Type); r = Ast.Write(v, value); } if (SpanHint != SourceSpan.Invalid || SpanHint != SourceSpan.None) { r.SetLoc(SpanHint); } return Ast.Void(r); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { var duration = (double)(stack.Pop().Value); var endSpeed = (double)(stack.Pop().Value); var b = (DmlBullet)bullet.Value; b.Components.Add(new TransitionSpeedComponent(b.Speed, endSpeed, b.LocalTime, duration)); }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { double second = (double)(stack.Pop().Value); double first = (double)(stack.Pop().Value); if (first <= second) block.currentPosition = position; }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { var weight = (float)(double)(stack.Pop().Value); var direction = (Vector2)(stack.Pop().Value); var b = (DmlBullet)(bullet.Value); b.Direction += weight * direction / 100f; }
public static void WithExtensions(Type extensions, CodeBlock block) { RegisterExtensions(extensions); try { block(); } finally { UnRegisterExtensions(extensions); } }
public void Perform( CodeBlock block, Stack<DmlObject> stack, Dictionary<string, DmlObject> locals, DmlObject bullet, DmlSystem system) { DmlObject second = stack.Pop(); DmlObject first = stack.Pop(); if (first.Type != DmlType.Number || second.Type != DmlType.Number) throw DmlSyntaxError.BadBinaryOperandTypes("<", first.Type, second.Type); stack.Push(new DmlObject(DmlType.Bool, (double)(first.Value) < (double)(second.Value))); }
// (clr-call type member obj arg1 ... ) public override Expression Generate(object args, CodeBlock cb) { Type t = null; string type = null; bool inferred = false; object rtype = Builtins.First(args); ExtractTypeInfo(rtype, out t, out type, out inferred); string member = null; var marg = Builtins.Second(args); object memobj = null; Type[] argtypes = null; Type[] gentypes = null; if (marg is SymbolId) { var mem = Builtins.SymbolValue(marg); if (mem is Cons) { ExtractMethodInfo(mem as Cons, out member, ref argtypes, ref gentypes); } else { ClrSyntaxError("clr-call", "type member not supported", mem); } } else { memobj = Builtins.Second(marg); member = memobj is SymbolId?SymbolTable.IdToString((SymbolId)memobj) : ""; if (memobj is string) { string mems = memobj as string; int bi = mems.IndexOf('('); if (bi < 0) { member = mems; } else { member = mems.Substring(0, bi); } } else if (memobj is Cons) { ExtractMethodInfo(memobj as Cons, out member, ref argtypes, ref gentypes); } } Expression instance = GetAst(Builtins.Third(args), cb); CallType ct = CallType.ImplicitInstance; if (instance is ConstantExpression && ((ConstantExpression)instance).Value == null) { ct = CallType.None; if (inferred) { ClrSyntaxError("clr-call", "type inference not possible on static member", member); } } else if (inferred) { if (instance is UnaryExpression && instance.Type == typeof(object)) { var ue = (UnaryExpression)instance; instance = ue.Operand; } t = instance.Type; } else { instance = ConvertToHelper(t, instance); } type = t.Name; Expression[] arguments = GetAstListNoCast(Cdddr(args) as Cons, cb); if (member == "get_Item") { if (Attribute.IsDefined(t, typeof(DefaultMemberAttribute))) { var dma = Attribute.GetCustomAttribute(t, typeof(DefaultMemberAttribute)) as DefaultMemberAttribute; member = "get_" + dma.MemberName; } else if (t.IsArray) { var index = arguments[0]; return(Ast.ArrayIndex(instance, Ast.ConvertHelper(index, typeof(int)))); } } else if (member == "set_Item") { if (Attribute.IsDefined(t, typeof(DefaultMemberAttribute))) { var dma = Attribute.GetCustomAttribute(t, typeof(DefaultMemberAttribute)) as DefaultMemberAttribute; member = "set_" + dma.MemberName; } else if (t.IsArray) { var index = arguments[0]; var v = arguments[1]; return(Ast.Comma(Ast.AssignArrayIndex(instance, Ast.ConvertHelper(index, typeof(int)), v), Ast.ReadField(null, Unspecified))); } } List <MethodBase> candidates = new List <MethodBase>(); BindingFlags bf = BindingFlags.Public | (ct == CallType.None ? BindingFlags.Static : BindingFlags.Instance) | BindingFlags.FlattenHierarchy; foreach (MethodInfo mi in t.GetMember(member, MemberTypes.Method, bf)) { if (mi.ContainsGenericParameters) { if (gentypes != null && mi.GetGenericArguments().Length == gentypes.Length) { candidates.Add(mi.MakeGenericMethod(gentypes)); continue; } } candidates.Add(mi); } Type[] types = new Type[arguments.Length]; for (int i = 0; i < types.Length; i++) { types[i] = arguments[i].Type; } if (memobj is string) { string mems = memobj as string; int bi = mems.IndexOf('('); if (bi < 0) { // do notthig } else { string[] typeargs = mems.Substring(bi + 1).TrimEnd(')').Split(','); for (int i = 0; i < types.Length; i++) { if (typeargs[i].Length > 0) { types[i] = ScanForType(typeargs[i]); } } } } else if (argtypes != null) { for (int i = 0; i < types.Length; i++) { types[i] = argtypes[i]; } } if (ct == CallType.ImplicitInstance) { types = ArrayUtils.Insert(t, types); } MethodBinder mb = MethodBinder.MakeBinder(Binder, member, candidates, BinderType.Normal); MethodCandidate mc = mb.MakeBindingTarget(ct, types); if (mc == null) { types = new Type[arguments.Length]; for (int i = 0; i < types.Length; i++) { types[i] = typeof(object); } if (ct == CallType.ImplicitInstance) { types = ArrayUtils.Insert(t, types); } mc = mb.MakeBindingTarget(ct, types); } if (mc != null) { MethodInfo meth = (MethodInfo)mc.Target.Method; // do implicit cast ParameterInfo[] pars = meth.GetParameters(); for (int i = 0; i < arguments.Length; i++) { Type tt = pars[i].ParameterType; arguments[i] = ConvertToHelper(tt, arguments[i]); } Expression r = null; // o god... if (ct == CallType.ImplicitInstance) { r = Ast.ComplexCallHelper(instance, (MethodInfo)mc.Target.Method, arguments); } else { r = Ast.ComplexCallHelper((MethodInfo)mc.Target.Method, arguments); } return(ConvertFromHelper(meth.ReturnType, r)); } ClrSyntaxError("clr-call", "member could not be resolved on type: " + type, args, member); return(null); }
public static CodeBlockExpression CodeBlockExpression(CodeBlock block, bool stronglyTyped, Type delegateType) { return(new CodeBlockExpression(block, false, stronglyTyped, true, delegateType)); }
// TODO: rename to CodeBlockDeclaration? public static CodeBlockExpression CodeBlockExpression(CodeBlock block, bool forceWrapper) { return(new CodeBlockExpression(block, forceWrapper, false, true, null)); }
/// <summary> /// Renders a code element. /// </summary> protected abstract void RenderCode(CodeBlock element, IRenderContext context);
/// <summary> /// Null coalescing expression (LINQ). /// {result} ::= ((tmp = {_left}) == null) ? {right} : tmp /// '??' operator in C#. /// </summary> public static Expression Coalesce(CodeBlock currentBlock, Expression left, Expression right) { return(CoalesceInternal(currentBlock, left, right, null, false)); }
public override Expression Generate(object args, CodeBlock c) { Cons lambdas = args as Cons; int arlen = lambdas == null ? 0 : lambdas.Length; if (arlen == 1) { if (lambdagen == null) { lambdagen = Context.Scope.LookupName(SymbolTable.StringToId("typed-lambda")) as TypedLambdaGenerator; } return(lambdagen.Generate(lambdas.car, c)); } else { List <CodeBlockDescriptor> cbs = new List <CodeBlockDescriptor>(); string lambdaname = GetLambdaName(c); NameHint = SymbolId.Empty; var sh = SpanHint; var lh = LocationHint; while (lambdas != null) { var refs = ClrGenerator.SaveReferences(); object actual = lambdas.car; object arg = Builtins.First(actual); object typespec = (Builtins.Second(actual)); Cons body = Builtins.Cdr(Builtins.Cdr(actual)) as Cons; var returntype = ClrGenerator.ExtractTypeInfo(Builtins.List(quote, Builtins.Second(typespec))); CodeBlock cb = Ast.CodeBlock(SpanHint, lambdaname, returntype); NameHint = SymbolId.Empty; cb.Filename = lh; cb.Parent = c; bool isrest = AssignParameters(cb, arg, Builtins.Car(typespec)); List <Statement> stmts = new List <Statement>(); FillBody(cb, stmts, body, true); Type dt = GetDelegateType(cb); Type ct = GetClosureType(cb); var cbe = Ast.CodeBlockExpression(cb, true, dt); Expression ex = Ast.New(ct.GetConstructor(new Type[] { dt }), cbe); CodeBlockDescriptor cbd = new CodeBlockDescriptor(); cbd.arity = isrest ? -cb.ParameterCount : cb.ParameterCount; cbd.callable = ex; cbd.codeblock = cbe; cbd.varargs = isrest; descriptorshack2.Add(cbd.callable, cbd); cbs.Add(cbd); lambdas = lambdas.cdr as Cons; ClrGenerator.ResetReferences(refs); } return(MakeTypedCaseClosure(lambdaname, cbs)); } }
/// <summary> /// Adds extra adornments to Code Block, if it contains a Language. /// </summary> /// <param name="element">CodeBlock Element</param> /// <param name="context">Render Context</param> protected override void RenderCode(CodeBlock element, IRenderContext context) { // Renders the Code Block in the standard fashion. base.RenderCode(element, context); // Don't do any manipulations if the CodeLanguage isn't specified. if (string.IsNullOrWhiteSpace(element.CodeLanguage)) { return; } // Unify all Code Language headers for C#. var language = element.CodeLanguage.ToUpper(); switch (language) { case "CSHARP": case "CS": language = "C#"; break; } // Grab the Local context and cast it. var localContext = context as UIElementCollectionRenderContext; var collection = localContext?.BlockUIElementCollection; // Don't go through with it, if there is an issue with the context or collection. if (localContext == null || collection?.Any() != true) { return; } var lastIndex = collection.Count() - 1; var prevIndex = lastIndex - 1; // Removes the current Code Block UI from the UI Collection, and wraps it in additional UI. if (collection[lastIndex] is ScrollViewer viewer) { collection.RemoveAt(lastIndex); // Combine Code Blocks if a Different Language. if (language != "XAML" && prevIndex >= 0 && collection[prevIndex] is StackPanel prevPanel && prevPanel.Tag is CustomCodeBlock block && !block.Languages.ContainsKey("XAML") && // Prevent combining of XAML Code Blocks. !block.Languages.ContainsKey(language)) { // Add New Lang to Existing Block #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly block.Languages.Add(language, (viewer, element.Text)); #pragma warning restore SA1008 // Opening parenthesis must be spaced correctly if (prevPanel.Children.FirstOrDefault() is Grid headerGrid) { var langHead = headerGrid.Children.FirstOrDefault(); if (langHead is TextBlock textLangHead) { // Replace TextBlock with ComboBox headerGrid.Children.Remove(textLangHead); var combLangHead = new ComboBox { Items = { textLangHead.Text, language }, SelectedIndex = 0, MinWidth = 80 }; headerGrid.Children.Add(combLangHead); combLangHead.SelectionChanged += (s, e) => { var newLang = combLangHead.SelectedItem as string; block.CurrentLanguage = newLang; LanguageRequested?.Invoke(combLangHead, newLang); var newViewer = block.Languages[newLang].viewer; // Remove old Viewer. var lastItem = prevPanel.Children.Count - 1; if (lastItem >= 0) { prevPanel.Children.RemoveAt(lastItem); } prevPanel.Children.Add(newViewer); }; LanguageRequested += (s, e) => { if (s != combLangHead) { if (combLangHead.Items.Contains(e)) { combLangHead.SelectedItem = e; block.CurrentLanguage = e; } } }; if (DesiredLang == language) { combLangHead.SelectedItem = language; block.CurrentLanguage = language; } } else if (langHead is ComboBox combLangHead) { // Add Lang to ComboBox #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly block.Languages.Add(language, (viewer, element.Text)); #pragma warning restore SA1008 // Opening parenthesis must be spaced correctly combLangHead.Items.Add(language); if (DesiredLang == language) { combLangHead.SelectedItem = language; block.CurrentLanguage = language; } } } } else { block = new CustomCodeBlock(); #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly block.Languages.Add(language, (viewer, element.Text)); #pragma warning restore SA1008 // Opening parenthesis must be spaced correctly block.CurrentLanguage = language; // Creates a Header to specify Language and provide a copy button. var headerGrid = new Grid { Background = new SolidColorBrush(Color.FromArgb(50, 0, 0, 0)) }; headerGrid.ColumnDefinitions.Add(new ColumnDefinition()); headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); var languageBlock = new TextBlock { Text = language, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(10, 0, 0, 0) }; headerGrid.Children.Add(languageBlock); var copyButton = new Button { Content = "Copy", HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch }; copyButton.Click += (s, e) => { var text = block.Languages[block.CurrentLanguage].text; var content = new DataPackage(); content.SetText(text); Clipboard.SetContent(content); }; headerGrid.Children.Add(copyButton); Grid.SetColumn(copyButton, 1); // Collection the adornment and the standard UI, add them to a StackPanel, and add it back to the collection. var panel = new StackPanel { Background = viewer.Background, Margin = viewer.Margin, Tag = block }; panel.Children.Add(headerGrid); panel.Children.Add(viewer); collection.Add(panel); } }
public void AddCommand(int codeBlockLocation) { CodeBlock codeBlock = GetCodeBlock(codeBlockLocation); PsaCommandHandler.AddCommand(codeBlock); }
public IfInstruction(CodeBlock cbIn) : base(cbIn) { }
/// <summary> /// Adds extra adornments to Code Block, if it contains a Language. /// </summary> /// <param name="element">CodeBlock Element</param> /// <param name="context">Render Context</param> protected override void RenderCode(CodeBlock element, IRenderContext context) { // Renders the Code Block in the standard fashion. base.RenderCode(element, context); // Don't do any manipulations if the CodeLanguage isn't specified. if (string.IsNullOrWhiteSpace(element.CodeLanguage)) { return; } // Unify all Code Language headers for C#. var language = element.CodeLanguage.ToUpper(); switch (language) { case "CSHARP": case "CS": language = "C#"; break; } // Grab the Local context and cast it. var localContext = context as UIElementCollectionRenderContext; var collection = localContext?.BlockUIElementCollection; // Don't go through with it, if there is an issue with the context or collection. if (localContext == null || collection?.Any() != true) { return; } var lastIndex = collection.Count() - 1; // Removes the current Code Block UI from the UI Collection, and wraps it in additional UI. if (collection[lastIndex] is ScrollViewer viewer) { collection.RemoveAt(lastIndex); // Creates a Header to specify Language and provide a copy button. var headerGrid = new Grid { Background = new SolidColorBrush(Color.FromArgb(17, 0, 0, 0)) }; headerGrid.ColumnDefinitions.Add(new ColumnDefinition()); headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); var languageBlock = new TextBlock { Text = language, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(10, 0, 0, 0) }; headerGrid.Children.Add(languageBlock); var copyButton = new Button { Content = "Copy", HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, FontSize = 11 }; copyButton.Click += (s, e) => { var content = new DataPackage(); content.SetText(element.Text); Clipboard.SetContent(content); }; headerGrid.Children.Add(copyButton); Grid.SetColumn(copyButton, 1); // Collection the adornment and the standard UI, add them to a Stackpanel, and add it back to the collection. var panel = new StackPanel(); panel.Children.Add(headerGrid); panel.Children.Add(viewer); panel.Background = viewer.Background; panel.Margin = viewer.Margin; collection.Add(panel); } }
public DmlBulletFactory(string name, CodeBlock init, CodeBlock update) { Name = name; Init = init; Update = update; }
private static AssignationModel BlockToModel(ICodeStruct currentBlock, RelayCommand <object> deleteCommand) { //Should never loop inside something other than an assignation, check type Assignation assignation = currentBlock as Assignation; if (assignation != null) { Assignation block = assignation; //Check if simply empty, consider an empty block if (block.Value == null) { //Simple assignation, return corresponding model return(new AssignationModel { BackgroundColor = BLOCKS_COLORS[0], BorderColor = BLOCKS_COLORS[1], Color = BLOCKS_COLORS[2], IsNotEditable = false, CanHaveChild = true, Code = Regex.Replace(block.Assignee, @"\t|\n|\r|\s", "") + " " + block.Operator + " {}", LocalizationKey = getAssignationName(block.Assignee), DeleteNodeCommand = deleteCommand }); } //check if a code value CodeValue value = block.Value as CodeValue; if (value != null) { //Simple assignation, return corresponding model return(new AssignationModel() { BackgroundColor = ASSIGNATIONS_COLORS[0], BorderColor = ASSIGNATIONS_COLORS[1], Color = ASSIGNATIONS_COLORS[2], IsNotEditable = false, CanHaveChild = false, Code = Regex.Replace(block.Assignee, @"\t|\n|\r|\s", "") + " " + block.Operator + " " + Regex.Replace(value.Value, @"\t|\n|\r|\s", ""), LocalizationKey = "Scripter_Assignation_Custom", DeleteNodeCommand = deleteCommand }); //Ignore childs even if there is some } //Otherwise, the child is a codeblock CodeBlock codeBlock = block.Value as CodeBlock; if (codeBlock != null) { AssignationModel newAssignation = new AssignationModel() { BackgroundColor = getColorArray(block.Assignee)[0], BorderColor = getColorArray(block.Assignee)[1], Color = getColorArray(block.Assignee)[2], IsNotEditable = false, CanHaveChild = true, Code = Regex.Replace(block.Assignee, @"\t|\n|\r|\s", "") + " " + block.Operator + " {}", LocalizationKey = getAssignationName(block.Assignee), DeleteNodeCommand = deleteCommand }; foreach (ICodeStruct code in codeBlock.Code) { newAssignation.Childrens.Add(BlockToModel(code, deleteCommand)); } return(newAssignation); } //Error, return nothing. return(null); } //If the current block is a code Value (Corrsponding to block = { Value } if (currentBlock is CodeValue) { //Print the value return(new AssignationModel() { BackgroundColor = ASSIGNATIONS_COLORS[0], BorderColor = ASSIGNATIONS_COLORS[1], Color = ASSIGNATIONS_COLORS[2], IsNotEditable = false, CanHaveChild = false, Code = Regex.Replace(currentBlock.Parse(), @"\t|\n|\r|\s", ""), LocalizationKey = "Scripter_Assignation_Custom", DeleteNodeCommand = deleteCommand }); } return(null); }
internal CodeBlockElement(CodeBlock codeBlock) : base(codeBlock) { this.DefaultStyleKey = typeof(CodeBlockElement); _codeBlock = codeBlock; }
/// <summary> /// Parses a markdown document. /// </summary> /// <param name="markdown"> The markdown text. </param> /// <param name="start"> The position to start parsing. </param> /// <param name="end"> The position to stop parsing. </param> /// <param name="quoteDepth"> The current nesting level for block quoting. </param> /// <param name="actualEnd"> Set to the position at which parsing ended. This can be /// different from <paramref name="end"/> when the parser is being called recursively. /// </param> /// <returns> A list of parsed blocks. </returns> internal static List <MarkdownBlock> Parse(string markdown, int start, int end, int quoteDepth, out int actualEnd) { // We need to parse out the list of blocks. // Some blocks need to start on a new paragraph (code, lists and tables) while other // blocks can start on any line (headers, horizontal rules and quotes). // Text that is outside of any other block becomes a paragraph. var blocks = new List <MarkdownBlock>(); int startOfLine = start; bool lineStartsNewParagraph = true; var paragraphText = new StringBuilder(); // These are needed to parse underline-style header blocks. int previousRealtStartOfLine = start; int previousStartOfLine = start; int previousEndOfLine = start; // Go line by line. while (startOfLine < end) { // Find the first non-whitespace character. int nonSpacePos = startOfLine; char nonSpaceChar = '\0'; int realStartOfLine = startOfLine; // i.e. including quotes. int expectedQuotesRemaining = quoteDepth; while (true) { while (nonSpacePos < end) { char c = markdown[nonSpacePos]; if (c == '\r' || c == '\n') { // The line is either entirely whitespace, or is empty. break; } if (c != ' ' && c != '\t') { // The line has content. nonSpaceChar = c; break; } nonSpacePos++; } // When parsing blocks in a blockquote context, we need to count the number of // quote characters ('>'). If there are less than expected AND this is the // start of a new paragraph, then stop parsing. if (expectedQuotesRemaining == 0) { break; } if (nonSpaceChar == '>') { // Expected block quote characters should be ignored. expectedQuotesRemaining--; nonSpacePos++; nonSpaceChar = '\0'; startOfLine = nonSpacePos; // Ignore the first space after the quote character, if there is one. if (startOfLine < end && markdown[startOfLine] == ' ') { startOfLine++; nonSpacePos++; } } else { int lastIndentation = 0; string lastline = null; // Determines how many Quote levels were in the last line. if (realStartOfLine > 0) { lastline = markdown.Substring(previousRealtStartOfLine, previousEndOfLine - previousRealtStartOfLine); lastIndentation = lastline.Count(c => c == '>'); } var currentEndOfLine = Common.FindNextSingleNewLine(markdown, nonSpacePos, end, out _); var currentline = markdown.Substring(realStartOfLine, currentEndOfLine - realStartOfLine); var currentIndentation = currentline.Count(c => c == '>'); var firstChar = markdown[realStartOfLine]; // This is a quote that doesn't start with a Quote marker, but carries on from the last line. if (lastIndentation == 1) { if (nonSpaceChar != '\0' && firstChar != '>') { break; } } // Collapse down a level of quotes if the current indentation is greater than the last indentation. // Only if the last indentation is greater than 1, and the current indentation is greater than 0 if (lastIndentation > 1 && currentIndentation > 0 && currentIndentation < lastIndentation) { break; } // This must be the end of the blockquote. End the current paragraph, if any. actualEnd = realStartOfLine; if (paragraphText.Length > 0) { blocks.Add(ParagraphBlock.Parse(paragraphText.ToString())); } return(blocks); } } // Find the end of the current line. int endOfLine = Common.FindNextSingleNewLine(markdown, nonSpacePos, end, out int startOfNextLine); if (nonSpaceChar == '\0') { // The line is empty or nothing but whitespace. lineStartsNewParagraph = true; // End the current paragraph. if (paragraphText.Length > 0) { blocks.Add(ParagraphBlock.Parse(paragraphText.ToString())); paragraphText.Clear(); } } else { // This is a header if the line starts with a hash character, // or if the line starts with '-' or a '=' character and has no other characters. // Or a quote if the line starts with a greater than character (optionally preceded by whitespace). // Or a horizontal rule if the line contains nothing but 3 '*', '-' or '_' characters (with optional whitespace). MarkdownBlock newBlockElement = null; if (nonSpaceChar == '-' && nonSpacePos == startOfLine) { // Yaml Header newBlockElement = YamlHeaderBlock.Parse(markdown, startOfLine, markdown.Length, out startOfLine); if (newBlockElement != null) { realStartOfLine = startOfLine; endOfLine = startOfLine + 3; startOfNextLine = Common.FindNextSingleNewLine(markdown, startOfLine, end, out startOfNextLine); } paragraphText.Clear(); } if (newBlockElement == null && nonSpaceChar == '#' && nonSpacePos == startOfLine) { // Hash-prefixed header. newBlockElement = HeaderBlock.ParseHashPrefixedHeader(markdown, startOfLine, endOfLine); } else if ((nonSpaceChar == '-' || nonSpaceChar == '=') && nonSpacePos == startOfLine && paragraphText.Length > 0) { // Underline style header. These are weird because you don't know you've // got one until you've gone past it. // Note: we intentionally deviate from reddit here in that we only // recognize this type of header if the previous line is part of a // paragraph. For example if you have this, the header at the bottom is // ignored: // a|b // -|- // 1|2 // === newBlockElement = HeaderBlock.ParseUnderlineStyleHeader(markdown, previousStartOfLine, previousEndOfLine, startOfLine, endOfLine); if (newBlockElement != null) { // We're going to have to remove the header text from the pending // paragraph by prematurely ending the current paragraph. // We already made sure that there is a paragraph in progress. paragraphText.Length = paragraphText.Length - (previousEndOfLine - previousStartOfLine); } } // These characters overlap with the underline-style header - this check should go after that one. if (newBlockElement == null && (nonSpaceChar == '*' || nonSpaceChar == '-' || nonSpaceChar == '_')) { newBlockElement = HorizontalRuleBlock.Parse(markdown, startOfLine, endOfLine); } if (newBlockElement == null && lineStartsNewParagraph) { // Some block elements must start on a new paragraph (tables, lists and code). int endOfBlock = startOfNextLine; if (nonSpaceChar == '*' || nonSpaceChar == '+' || nonSpaceChar == '-' || (nonSpaceChar >= '0' && nonSpaceChar <= '9')) { newBlockElement = ListBlock.Parse(markdown, realStartOfLine, end, quoteDepth, out endOfBlock); } if (newBlockElement == null && (nonSpacePos > startOfLine || nonSpaceChar == '`')) { newBlockElement = CodeBlock.Parse(markdown, realStartOfLine, end, quoteDepth, out endOfBlock); } if (newBlockElement == null) { newBlockElement = TableBlock.Parse(markdown, realStartOfLine, endOfLine, end, quoteDepth, out endOfBlock); } if (newBlockElement != null) { startOfNextLine = endOfBlock; } } // This check needs to go after the code block check. if (newBlockElement == null && nonSpaceChar == '>') { newBlockElement = QuoteBlock.Parse(markdown, realStartOfLine, end, quoteDepth, out startOfNextLine); } // This check needs to go after the code block check. if (newBlockElement == null && nonSpaceChar == '[') { newBlockElement = LinkReferenceBlock.Parse(markdown, startOfLine, endOfLine); } // Block elements start new paragraphs. lineStartsNewParagraph = newBlockElement != null; if (newBlockElement == null) { // The line contains paragraph text. if (paragraphText.Length > 0) { // If the previous two characters were both spaces, then append a line break. if (paragraphText.Length > 2 && paragraphText[paragraphText.Length - 1] == ' ' && paragraphText[paragraphText.Length - 2] == ' ') { // Replace the two spaces with a line break. paragraphText[paragraphText.Length - 2] = '\r'; paragraphText[paragraphText.Length - 1] = '\n'; } else { paragraphText.Append(" "); } } // Add the last paragraph if we are at the end of the input text. if (startOfNextLine >= end) { if (paragraphText.Length == 0) { // Optimize for single line paragraphs. blocks.Add(ParagraphBlock.Parse(markdown.Substring(startOfLine, endOfLine - startOfLine))); } else { // Slow path. paragraphText.Append(markdown.Substring(startOfLine, endOfLine - startOfLine)); blocks.Add(ParagraphBlock.Parse(paragraphText.ToString())); } } else { paragraphText.Append(markdown.Substring(startOfLine, endOfLine - startOfLine)); } } else { // The line contained a block. End the current paragraph, if any. if (paragraphText.Length > 0) { blocks.Add(ParagraphBlock.Parse(paragraphText.ToString())); paragraphText.Clear(); } blocks.Add(newBlockElement); } } // Repeat. previousRealtStartOfLine = realStartOfLine; previousStartOfLine = startOfLine; previousEndOfLine = endOfLine; startOfLine = startOfNextLine; } actualEnd = startOfLine; return(blocks); }
public WhileInstruction(CodeBlock cbIn) : base(cbIn) { }
public IEnumerable <CodeBlock> CreateCreateCommandMethodBody() { var sp = this.StoredProcedure; String pName = ""; switch (this.StoredProcedure.DatabaseServer) { case DatabaseServer.SqlServer: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "var db = new SqlServerDatabase(\"\");")); break; case DatabaseServer.MySql: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "var db = new MySqlDatabase(\"\");")); break; case DatabaseServer.Oracle: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "var db = new OracleDatabase(\"\");")); break; case DatabaseServer.PostgreSql: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "var db = new PostgreSqlDatabase(\"\");")); break; default: throw new InvalidOperationException(); } yield return(new CodeBlock(SourceCodeLanguage.CSharp, "var cm = db.CreateCommand();")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "cm.CommandType = CommandType.StoredProcedure;")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "cm.CommandText = this.GetStoredProcedureName();")); if (sp.Parameters.Count > 0) { yield return(new CodeBlock(SourceCodeLanguage.CSharp, "")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "DbParameter p = null;")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "")); foreach (var parameter in sp.Parameters) { pName = parameter.GetNameWithoutAtmark(); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p = db.CreateParameter(\"{0}\", {1}, {2}, {3});" , parameter.Name, parameter.DbType.GetDbTypeCodeBlock() , parameter.Precision.HasValue ? parameter.Precision.ToString() : "null" , parameter.Scale.HasValue ? parameter.Scale.ToString(): "null")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.SourceColumn = p.ParameterName;")); switch (parameter.ParameterDirection) { case ParameterDirection.Input: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Direction = ParameterDirection.Input;")); break; case ParameterDirection.InputOutput: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Direction = ParameterDirection.InputOutput;")); break; case ParameterDirection.Output: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Direction = ParameterDirection.Output;")); break; case ParameterDirection.ReturnValue: yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Direction = ParameterDirection.ReturnValue;")); break; default: throw new InvalidOperationException(); } if (parameter.Length.HasValue == true) { yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Size = {0};", parameter.Length)); } if (parameter.DbType.IsStructured() == true) { yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.SetTypeName(\"{0}\");", parameter.UserTableTypeName)); } if (parameter.DbType.IsUdt() == true) { yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.SetUdtTypeName(\"{0}\");", parameter.UdtTypeName)); } switch (parameter.ConvertType) { case SqlParameterConvertType.Default: if (parameter.DbType.IsUserDefinedTableType() == true) { var dtCodeBlock = new CodeBlock(SourceCodeLanguage.CSharp, ""); dtCodeBlock.CurlyBracket = true; dtCodeBlock.CodeBlocks.Add(new CodeBlock(SourceCodeLanguage.CSharp, "var dt = this.{0}.CreateDataTable();", pName)); var foreachCodeBlock = new CodeBlock(SourceCodeLanguage.CSharp, "foreach (var item in this.{0}.Records)", pName); foreachCodeBlock.CurlyBracket = true; foreachCodeBlock.CodeBlocks.Add(new CodeBlock(SourceCodeLanguage.CSharp, "dt.Rows.Add(item.GetValues());")); dtCodeBlock.CodeBlocks.Add(foreachCodeBlock); dtCodeBlock.CodeBlocks.Add(new CodeBlock(SourceCodeLanguage.CSharp, "p.Value = dt;")); yield return(dtCodeBlock); } else { yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Value = this.{0};", pName)); } break; case SqlParameterConvertType.Enum: var methodName = "ToStringFromEnum"; if (parameter.AllowNull == true) { methodName = "ToStringOrNullFromEnum"; } yield return(new CodeBlock(SourceCodeLanguage.CSharp, "p.Value = this.{0}.{1}();", pName, methodName)); break; default: throw new InvalidOperationException(); } yield return(new CodeBlock(SourceCodeLanguage.CSharp, "cm.Parameters.Add(p);")); yield return(new CodeBlock(SourceCodeLanguage.CSharp, "")); } var cb = new CodeBlock(SourceCodeLanguage.CSharp, "for (int i = 0; i < cm.Parameters.Count; i++)"); cb.CurlyBracket = true; cb.CodeBlocks.Add(new CodeBlock(SourceCodeLanguage.CSharp, "if (cm.Parameters[i].Value == null) cm.Parameters[i].Value = DBNull.Value;")); yield return(cb); } yield return(new CodeBlock(SourceCodeLanguage.CSharp, "return cm;")); }
public override void Accept(CodeBlock scope) { symbolTable.EnterScope(); scope.VisitChildren(this); symbolTable.ExitScope(); }
public override Expression Generate(object args, CodeBlock cb) { return(GetCons(Builtins.Car(args), cb)); }
/// <summary> /// False coalescing expression. /// {result} ::= IsTrue(tmp = {left}) ? tmp : {right} /// Generalized OR semantics. /// </summary> public static Expression CoalesceFalse(CodeBlock currentBlock, Expression left, Expression right, MethodInfo isTrue) { Contract.RequiresNotNull(isTrue, "isTrue"); return(CoalesceInternal(currentBlock, left, right, isTrue, true)); }
public SymbolNode GetSymbolInFunction(string name, int classScope, int functionScope, CodeBlock codeBlock) { Validity.Assert(functionScope != Constants.kGlobalScope); if (Constants.kGlobalScope == functionScope) { return(null); } int symbolIndex = Constants.kInvalidIndex; if (classScope != Constants.kGlobalScope) { //Search local variable for the class member function symbolIndex = ClassTable.ClassNodes[classScope].symbols.IndexOf(name, classScope, functionScope); if (symbolIndex != Constants.kInvalidIndex) { return(ClassTable.ClassNodes[classScope].symbols.symbolList[symbolIndex]); } //Search class members symbolIndex = ClassTable.ClassNodes[classScope].symbols.IndexOf(name, classScope, Constants.kGlobalScope); if (symbolIndex != Constants.kInvalidIndex) { return(ClassTable.ClassNodes[classScope].symbols.symbolList[symbolIndex]); } } while (symbolIndex == Constants.kInvalidIndex && codeBlock != null && codeBlock.blockType != CodeBlockType.kFunction) { symbolIndex = codeBlock.symbolTable.IndexOf(name, classScope, functionScope); if (symbolIndex != Constants.kInvalidIndex) { return(codeBlock.symbolTable.symbolList[symbolIndex]); } else { codeBlock = codeBlock.parent; } } if (symbolIndex == Constants.kInvalidIndex && codeBlock != null && codeBlock.blockType == CodeBlockType.kFunction) { symbolIndex = codeBlock.symbolTable.IndexOf(name, classScope, functionScope); if (symbolIndex != Constants.kInvalidIndex) { return(codeBlock.symbolTable.symbolList[symbolIndex]); } } return(null); }
public static CodeBlockExpression CodeBlockReference(CodeBlock block, Type delegateType) { return(new CodeBlockExpression(block, false, false, false, delegateType)); }
public SymbolNode GetFirstVisibleSymbol(string name, int classscope, int function, CodeBlock codeblock) { // // Validity.Assert(null != codeblock); if (null == codeblock) { return(null); } int symbolIndex = Constants.kInvalidIndex; bool stillInsideFunction = function != Constants.kInvalidIndex; CodeBlock searchBlock = codeblock; // TODO(Jiong): Code Duplication, Consider moving this if else block inside the while loop if (stillInsideFunction) { symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, function); if (function != Constants.kInvalidIndex && searchBlock.procedureTable != null && searchBlock.procedureTable.procList.Count > function && // Note: This check assumes we can not define functions inside a fucntion symbolIndex == Constants.kInvalidIndex) { symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, Constants.kInvalidIndex); } } else { symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, Constants.kInvalidIndex); } while (Constants.kInvalidIndex == symbolIndex) { // if the search block is of type function, it means our search has gone out of the function itself // so, we should ignore the given function index and only search its parent block's global variable if (searchBlock.blockType == CodeBlockType.kFunction) { stillInsideFunction = false; } searchBlock = searchBlock.parent; if (null == searchBlock) { return(null); } // Continue searching if (stillInsideFunction) { // we are still inside a function, first search the local variable defined in this function // if not found, then search the enclosing block by specifying the function index as -1 symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, function); // this check is to avoid unnecessary search // for example if we have a for loop inside an imperative block which is further inside a function // when we are searching inside the for loop or language block, there is no need to search twice // we need to search twice only when we are searching directly inside the function, if (function != Constants.kInvalidIndex && searchBlock.procedureTable != null && searchBlock.procedureTable.procList.Count > function && // Note: This check assumes we can not define functions inside a fucntion symbolIndex == Constants.kInvalidIndex) { symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, Constants.kInvalidIndex); } } else { symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, Constants.kInvalidIndex); } } return(searchBlock.symbolTable.symbolList[symbolIndex]); }
public static CodeBlockExpression CodeBlockExpression(CodeBlock block, bool forceWrapper, bool stronglyTyped) { return(new CodeBlockExpression(block, forceWrapper, stronglyTyped, true, null)); }
private bool CheckLinesContent(IRepository repository, IScmData scmData, string testRevision, ProjectFile file, bool resultOnly) { IBlame fileBlame = null; try { fileBlame = scmData.Blame(testRevision, file.Path); } catch { } if (fileBlame == null) { if (!resultOnly) { Console.WriteLine("File {0} does not exist.", file.Path); } return(false); } double currentLOC = repository.SelectionDSL() .Commits().TillRevision(testRevision) .Files().IdIs(file.ID) .Modifications().InCommits().InFiles() .CodeBlocks().InModifications() .CalculateLOC(); bool correct = currentLOC == fileBlame.Count; if (!correct) { if (!resultOnly) { Console.WriteLine("Incorrect number of lines in file {0}. {1} should be {2}", file.Path, currentLOC, fileBlame.Count ); } else { return(false); } } SmartDictionary <string, int> linesByRevision = new SmartDictionary <string, int>(x => 0); foreach (var line in fileBlame) { linesByRevision[line.Value]++; } var codeBySourceRevision = ( from f in repository.Queryable <ProjectFile>() join m in repository.Queryable <Modification>() on f.ID equals m.FileID join cb in repository.Queryable <CodeBlock>() on m.ID equals cb.ModificationID join c in repository.Queryable <Commit>() on m.CommitID equals c.ID let addedCodeBlock = repository.Queryable <CodeBlock>() .Single(x => x.ID == (cb.Size < 0 ? cb.TargetCodeBlockID : cb.ID)) let codeAddedInitiallyInRevision = repository.Queryable <Commit>() .Single(x => x.ID == addedCodeBlock.AddedInitiallyInCommitID) .Revision let testRevisionNumber = repository.Queryable <Commit>() .Single(x => x.Revision == testRevision) .OrderedNumber where f.ID == file.ID && c.OrderedNumber <= testRevisionNumber group cb.Size by codeAddedInitiallyInRevision into g select new { FromRevision = g.Key, CodeSize = g.Sum() } ).Where(x => x.CodeSize != 0).ToList(); var errorCode = ( from codeFromRevision in codeBySourceRevision where codeFromRevision.CodeSize != linesByRevision[codeFromRevision.FromRevision] select new { SourceRevision = codeFromRevision.FromRevision, CodeSize = codeFromRevision.CodeSize, RealCodeSize = linesByRevision[codeFromRevision.FromRevision] } ).ToList(); correct = correct && codeBySourceRevision.Count() == linesByRevision.Count && errorCode.Count == 0; if (!resultOnly) { if (codeBySourceRevision.Count() != linesByRevision.Count) { Console.WriteLine("Number of revisions file {0} contains code from is incorrect. {1} should be {2}", file.Path, codeBySourceRevision.Count(), linesByRevision.Count ); } foreach (var error in errorCode) { Console.WriteLine("Incorrect number of lines in file {0} from revision {1}. {2} should be {3}", file.Path, error.SourceRevision, error.CodeSize, error.RealCodeSize ); } if ((!correct) && (errorCode.Count > 0)) { string latestCodeRevision = repository.LastRevision(errorCode.Select(x => x.SourceRevision)); var commitsFileTouchedIn = repository.SelectionDSL() .Files().IdIs(file.ID) .Commits().FromRevision(latestCodeRevision).TouchFiles() .OrderBy(c => c.OrderedNumber); foreach (var commit in commitsFileTouchedIn) { if (!CheckLinesContent(repository, scmData, commit.Revision, file, true)) { Console.WriteLine("{0} - incorrectly mapped commit.", commit.Revision); if ((automaticallyFixDiffErrors) && (errorCode.Sum(x => x.CodeSize - x.RealCodeSize) == 0)) { var incorrectDeleteCodeBlocks = from cb in repository.SelectionDSL() .Commits().RevisionIs(commit.Revision) .Files().PathIs(file.Path) .Modifications().InCommits().InFiles() .CodeBlocks().InModifications().Deleted() join tcb in repository.Queryable <CodeBlock>() on cb.TargetCodeBlockID equals tcb.ID join m in repository.Queryable <Modification>() on tcb.ModificationID equals m.ID join c in repository.Queryable <Commit>() on m.CommitID equals c.ID where errorCode.Select(x => x.SourceRevision).Contains(c.Revision) select new { Code = cb, TargetRevision = c.Revision }; foreach (var error in errorCode) { var incorrectDeleteCodeBlock = incorrectDeleteCodeBlocks.SingleOrDefault(x => x.TargetRevision == error.SourceRevision); var codeBlock = incorrectDeleteCodeBlock == null ? null : incorrectDeleteCodeBlock.Code; double difference = error.CodeSize - error.RealCodeSize; if (codeBlock == null) { codeBlock = new CodeBlock() { Size = 0, Modification = repository.SelectionDSL() .Commits().RevisionIs(commit.Revision) .Files().PathIs(file.Path) .Modifications().InCommits().InFiles().Single(), }; repository.Add(codeBlock); } Console.WriteLine("Fix code block size for file {0} in revision {1}:", file.Path, commit.Revision); Console.Write("Was {0}", codeBlock.Size); codeBlock.Size -= difference; if (codeBlock.Size == 0) { repository.Delete(codeBlock); } else if ((codeBlock.Size > 0) && (codeBlock.AddedInitiallyInCommitID == null)) { codeBlock.AddedInitiallyInCommit = commit; } else if ((codeBlock.Size < 0) && (codeBlock.TargetCodeBlockID == null)) { codeBlock.TargetCodeBlock = repository.SelectionDSL() .Commits().RevisionIs(error.SourceRevision) .Files().PathIs(file.Path) .Modifications().InFiles() .CodeBlocks().InModifications().AddedInitiallyInCommits().Single(); } Console.WriteLine(", now {0}", codeBlock.Size); } } break; } } } } return(correct); }
// (clr-new type arg1 ... ) public override Expression Generate(object args, CodeBlock cb) { Type t; string type; bool inferred; object rtype = Builtins.First(args); ExtractTypeInfo(rtype, out t, out type, out inferred); if (t == null) { ClrSyntaxError("clr-new", "type not found", type); } Expression[] arguments = GetAstListNoCast(Builtins.Cdr(args) as Cons, cb); List <MethodBase> candidates = new List <MethodBase>(); foreach (ConstructorInfo c in t.GetConstructors()) { bool add = true; foreach (var pi in c.GetParameters()) { if (pi.ParameterType.IsPointer) { add = false; break; } } if (add) { candidates.Add(c); } } if (t.IsValueType && arguments.Length == 0) { // create default valuetype here return(Ast.DefaultValueType(t)); } Type[] types = new Type[arguments.Length]; for (int i = 0; i < types.Length; i++) { types[i] = arguments[i].Type; } CallType ct = CallType.None; MethodBinder mb = MethodBinder.MakeBinder(Binder, "ctr", candidates, BinderType.Normal); MethodCandidate mc = mb.MakeBindingTarget(ct, types); if (mc == null) { types = new Type[arguments.Length]; for (int i = 0; i < types.Length; i++) { types[i] = typeof(object); } if (ct == CallType.ImplicitInstance) { types = ArrayUtils.Insert(t, types); } mc = mb.MakeBindingTarget(ct, types); } ConstructorInfo ci = null; if (mc == null && candidates.Count > 0) { foreach (ConstructorInfo c in candidates) { if (c.GetParameters().Length == arguments.Length) { ci = c; break; // tough luck for now } } } else { ci = mc.Target.Method as ConstructorInfo; } if (ci != null) { ParameterInfo[] pars = ci.GetParameters(); for (int i = 0; i < arguments.Length; i++) { Type tt = pars[i].ParameterType; arguments[i] = ConvertToHelper(tt, arguments[i]); } Expression r = Ast.New(ci, arguments); return(r); } ClrSyntaxError("clr-new", "constructor could not be resolved on type: " + type, args); return(null); }
public static ProcedureNode GetFirstVisibleProcedure(string name, List <Type> argTypeList, CodeBlock codeblock) { if (null == codeblock) { return(null); } CodeBlock searchBlock = codeblock; while (null != searchBlock) { if (null == searchBlock.procedureTable) { searchBlock = searchBlock.parent; continue; } // The class table is passed just to check for coercion values int procIndex = searchBlock.procedureTable.IndexOf(name, argTypeList); if (Constants.kInvalidIndex != procIndex) { return(searchBlock.procedureTable.procList[procIndex]); } searchBlock = searchBlock.parent; } return(null); }
public override Expression Generate(object args, CodeBlock cb) { return(Ast.Constant(new IronSchemeConstant(Cons.FromList(namespaces.Keys), cb))); }
public override void Accept(CodeBlock scope) { errorLog.AddError(ErrorType.ParserError, scope.Location, "statement can not exist inside pattern!"); }
private void AssertQueryIsOptimized(CodeBlock action) { action(); Assert.AreEqual(0, _collector.Diagnostics.Count); }
public override Expression Generate(object args, CodeBlock c) { var refs = ClrGenerator.SaveReferences(); level++; NameHint = SymbolTable.StringToId(""); CodeBlock cb = Ast.CodeBlock(SpanHint, GetLambdaName(c)); cb.Parent = c; List <Variable> vars = new List <Variable>(); List <Variable> temps = new List <Variable>(); List <object> defs = new List <object>(); Cons a = (args as Cons).car as Cons; while (a != null) { Cons d = a.car as Cons; Variable t = cb.CreateVariable((SymbolId)Builtins.GenSym(d.car), Variable.VariableKind.Temporary, typeof(object)); temps.Add(t); Variable r = Create((SymbolId)d.car, cb, typeof(object)); r.SetUnInitialized(); vars.Add(r); defs.Add(((Cons)d.cdr).car); a = a.cdr as Cons; } List <Statement> stmts = new List <Statement>(); var notstrict = !ScriptDomainManager.Options.StrictMode; for (int i = 0; i < vars.Count; i++) { NameHint = Builtins.UnGenSymInternal(vars[i].Name); //VarHint = vars[i].Name; Expression e = GetAst(defs[i], cb); if (e is MethodCallExpression) { MethodCallExpression mce = (MethodCallExpression)e; if (mce.Method == Closure_Make || mce.Method == Closure_MakeCase || mce.Method == Closure_MakeVarArgsX) { if (notstrict) { vars[i].SetInitialized(); temps[i].Type = vars[i].Type = typeof(Callable); } } } else if (e is NewExpression) { var ne = (NewExpression)e; if (typeof(ITypedCallable).IsAssignableFrom(ne.Type)) { if (notstrict) { vars[i].SetInitialized(); temps[i].Type = vars[i].Type = ne.Type; } } } if (e is UnaryExpression && e.NodeType == AstNodeType.Convert && e.Type != typeof(object)) { if (notstrict) { temps[i].Type = vars[i].Type = e.Type; } } else if (e.Type.IsValueType) { e = Ast.ConvertHelper(e, typeof(object)); } stmts.Add(Ast.Write(temps[i], e)); } for (int i = 0; i < vars.Count; i++) { stmts.Add(Ast.Write(vars[i], temps[i])); } NameHint = SymbolId.Invalid; Cons body = Builtins.Cdr(args) as Cons; FillBody(cb, stmts, body, true); #if OPTIMIZATIONS Expression ex = InlineCall(c, Ast.CodeBlockExpression(cb, false)); #else Expression ex = Ast.SimpleCallHelper(MakeClosure(cb, false), GetCallable(0)); #endif level--; ClrGenerator.ResetReferences(refs); return(ex); }