Example #1
0
File: Scope.cs Project: plioi/rook
        public GlobalScope()
        {
            globals = new BindingDictionary();

            DataType @int  = NamedType.Integer;
            DataType @bool = NamedType.Boolean;

            DataType integerOperation  = NamedType.Function(new[] { @int, @int }, @int);
            DataType integerComparison = NamedType.Function(new[] { @int, @int }, @bool);
            DataType booleanOperation  = NamedType.Function(new[] { @bool, @bool }, @bool);

            globals["<"]  = integerComparison;
            globals["<="] = integerComparison;
            globals[">"]  = integerComparison;
            globals[">="] = integerComparison;
            globals["=="] = integerComparison;
            globals["!="] = integerComparison;

            globals["+"] = integerOperation;
            globals["*"] = integerOperation;
            globals["/"] = integerOperation;
            globals["-"] = integerOperation;

            globals["&&"] = booleanOperation;
            globals["||"] = booleanOperation;
            globals["!"]  = NamedType.Function(new[] { @bool }, @bool);

            var T = TypeVariable.CreateGeneric(); //TypeVariable 0
            var S = TypeVariable.CreateGeneric(); //TypeVariable 1

            var enumerableT = NamedType.Enumerable(T);
            var nullableT   = NamedType.Nullable(T);
            var vectorT     = NamedType.Vector(T);
            var enumerableS = NamedType.Enumerable(S);

            globals["??"]                   = NamedType.Function(new DataType[] { nullableT, T }, T);
            globals["Print"]                = NamedType.Function(new[] { T }, NamedType.Void);
            globals["Nullable"]             = NamedType.Function(new[] { T }, nullableT);
            globals["First"]                = NamedType.Function(new[] { enumerableT }, T);
            globals["Take"]                 = NamedType.Function(new[] { enumerableT, @int }, enumerableT);
            globals["Skip"]                 = NamedType.Function(new[] { enumerableT, @int }, enumerableT);
            globals["Any"]                  = NamedType.Function(new[] { enumerableT }, @bool);
            globals["Count"]                = NamedType.Function(new[] { enumerableT }, @int);
            globals["Select"]               = NamedType.Function(new[] { enumerableT, NamedType.Function(new[] { T }, S) }, enumerableS);
            globals["Where"]                = NamedType.Function(new[] { enumerableT, NamedType.Function(new[] { T }, @bool) }, enumerableT);
            globals["Each"]                 = NamedType.Function(new[] { vectorT }, enumerableT);
            globals[ReservedName.__index__] = NamedType.Function(new[] { vectorT, @int }, T);
            globals[ReservedName.__slice__] = NamedType.Function(new[] { vectorT, @int, @int }, vectorT);
            globals["Append"]               = NamedType.Function(new DataType[] { vectorT, T }, vectorT);
            globals["With"]                 = NamedType.Function(new[] { vectorT, @int, T }, vectorT);
        }
Example #2
0
 public void FailsTypeCheckingForNamesThatAreNotConstructorNames()
 {
     ShouldFailTypeChecking("new Foo()", Foo => Integer).WithError("Cannot construct 'Foo' because it is not a type.", 1, 5);
     ShouldFailTypeChecking("new Foo()", Foo => NamedType.Function(Integer)).WithError("Cannot construct 'Foo' because it is not a type.", 1, 5);
 }
        public ExecutionDocumentWalkerOptions Add(object visitor)
        {
            if (visitor is IVisit <ExecutableDocument> ed)
            {
                ExecutableDocument.Add(ed);
            }

            if (visitor is IVisit <FragmentDefinition> fd)
            {
                FragmentDefinition.Add(fd);
            }

            if (visitor is IVisit <OperationDefinition> od)
            {
                OperationDefinition.Add(od);
            }

            if (visitor is IVisit <SelectionSet> ss)
            {
                SelectionSet.Add(ss);
            }


            if (visitor is IVisit <ISelection> s)
            {
                Selection.Add(s);
            }

            if (visitor is IVisit <FieldSelection> fs)
            {
                FieldSelection.Add(fs);
            }

            if (visitor is IVisit <InlineFragment> ift)
            {
                InlineFragment.Add(ift);
            }

            if (visitor is IVisit <FragmentSpread> fgs)
            {
                FragmentSpread.Add(fgs);
            }

            if (visitor is IVisit <Argument> arg)
            {
                Argument.Add(arg);
            }

            if (visitor is IVisit <NamedType> nt)
            {
                NamedType.Add(nt);
            }

            if (visitor is IVisit <VariableDefinition> vd)
            {
                VariableDefinition.Add(vd);
            }

            if (visitor is IVisit <DefaultValue> dv)
            {
                DefaultValue.Add(dv);
            }

            if (visitor is IVisit <Value> v)
            {
                Value.Add(v);
            }

            if (visitor is IVisit <Directive> d)
            {
                Directive.Add(d);
            }

            if (visitor is IVisit <TypeBase> t)
            {
                Type.Add(t);
            }

            return(this);
        }
Example #4
0
 public override Void Visit(NamedType node, Void param)
 {
     Debug.Assert(false, $"{nameof(NamedType)} reached but it should have been removed already");
     return(base.Visit(node, param));
 }
 protected bool Equals(NamedType other)
 {
     return(string.Equals(Name, other.Name));
 }
 public override object Visit(NamedType that, object value = null)
 {
     // Attempt to recursively resolve the reference, starting at the appropriate scope and looking upwards.
     return that.Reference.Visit(this, value);
 }
        public override object Visit(NamedType that, object value = null)
        {
            PrintPrologue(that);
            _writer.WriteLine("TypeKind = {0}", that.TypeKind.ToString());
            PrintNodeId("Reference", that.Reference);
            PrintNodeId("Type", that.Type);
            PrintEpilogue(that);

            that.Reference.Visit(this);
            that.Type.Visit(this);

            return null;
        }
Example #8
0
        protected string GetCSTypeFull(NamedType type)
        {
            var fullName = TypeHelper.GetCSType(type, Settings, false, false, GetFullNamespace(type, Settings.Namespace, Settings.Structure));

            return(TrimNamespace(fullName));
        }
Example #9
0
 private static DataType Function(IEnumerable <DataType> parameterTypes, DataType returnType)
 {
     return(NamedType.Function(parameterTypes, returnType));
 }
Example #10
0
 public static int GetHashCode(Type type, string?name)
 => NamedType.GetHashCode(type, name) & UnityContainer.HashMask;
Example #11
0
        /** Parses a \c guard definition, which makes a \c value accessible through the a getter and/or a setter.
         *
         *  guard Foo is io .foo:
         *       get:
         *           return .foo
         *       set:
         *           .foo := 2 * value
         */
        private GuardStatement ParseGuardStatement()
        {
            Token start = _matcher.Match(TokenKind.Keyword_Guard);
            _matcher.Match(TokenKind.Space);
            SymbolDefinition name = ParseSymbolDefinition(SymbolKind.Guard);
            #if false
            Token @base = null;
            if (_matcher.This.Kind == TokenKind.Dot)
            {
                _matcher.Match(TokenKind.Dot);
                @base = name;
                @name = _matcher.Match(TokenKind.Name);
            }
            #endif
            _matcher.Match(TokenKind.Space);
            _matcher.Match(TokenKind.Keyword_Is);
            _matcher.Match(TokenKind.Space);
            DirectionKind direction = ParseDirection();
            _matcher.Match(TokenKind.Space);
            #if DONE
            Expression member = ParseInstanceExpression();
            #else
            _matcher.Match(TokenKind.Dot);
            Token token = _matcher.Match(TokenKind.Name);
            SymbolReference reference = new SymbolReference(token.Cursor, PathKind.Instance, token.Text);
            Type type = new NamedType(token.Cursor, reference);
            #endif

            Statement getter = null;
            Statement setter = null;
            if (_matcher.This.Kind == TokenKind.Colon)
            {
                _matcher.Match(TokenKind.Colon);
                _matcher.Match(TokenKind.EndOfLine);
                token = _matcher.Match(TokenKind.Indent);     // NOTE: Update 'token'!
                switch (direction)
                {
                    case DirectionKind.Out:
                        getter = ParseGetRoutine((Type) type.Clone());
                        break;

                    case DirectionKind.In:
                        setter = ParseSetRoutine((Type) type.Clone());
                        break;

                    case DirectionKind.InOut:
                        if (_matcher.This.Kind == TokenKind.Keyword_Get)
                            getter = ParseGetRoutine((Type) type.Clone());
                        if (_matcher.This.Kind == TokenKind.Keyword_Set)
                            setter = ParseSetRoutine((Type) type.Clone());
                        if (getter == null && setter == null)
                            throw new ParserError(token.Cursor, "Getter or setter must be specified after colon");
                        break;

                    default:
                        throw new System.ArgumentException("direction");
                }
                _matcher.Match(TokenKind.Dedent);
            }

            if (getter == null)
            {
                if (direction != DirectionKind.In)
                    getter = CreateDefaultGetter(token.Cursor, token.Text);
                else
                    getter = new NoneStatement(token.Cursor);
            }

            if (setter == null)
            {
                if (direction != DirectionKind.Out)
                    setter = CreateDefaultSetter(token.Cursor, token.Text);
                else
                    setter = new NoneStatement(token.Cursor);
            }

            return new GuardStatement(start.Cursor, name, direction, type, getter, setter);
        }
Example #12
0
 public static int GetHashCode(Type type)
 => NamedType.GetHashCode(type.GetHashCode(), -1) & UnityContainer.HashMask;
Example #13
0
 public virtual void Enter(NamedType namedType)
 {
 }
Example #14
0
 public virtual void Leave(NamedType namedType)
 {
 }
 public KnownTypeNamesError(ValidationContext context, NamedType node, string[] suggestedTypes)
     : base(context.OriginalQuery, NUMBER, UnknownTypeMessage(node.Name, suggestedTypes), node)
 {
 }
Example #16
0
 public void Add(NamedType namedType)
 {
     this.typeNames.Add(namedType);
 }
Example #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            string       location   = args.Length > 0 ? args[0] : Console.ReadLine();
            const string argStart   = "--converter:";
            string       converterV = args.FirstOrDefault(v => v.StartsWith(argStart));

            if (converterV == null)
            {
                Console.WriteLine(@"What software would you like to convert for?
Currently Supported:
Bridge,
DuoCode");
            }
            string converterValue = converterV == null?Console.ReadLine() : converterV.Substring(argStart.Length);

            ConversionSoftware conversionSoftware = (ConversionSoftware)Enum.Parse(typeof(ConversionSoftware), converterValue);
            string             file;

            Console.WriteLine("Reading file...");
            try
            {
                file = File.ReadAllText(location);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }
            var parser = new MTypescriptParser
            {
                ParseString = file
            };

            Console.WriteLine("Parsing...");
            parser.Parse();
            Namespace globalNamespace = parser.globalNamespace;
            var       converter       = new TypescriptToCSConverter(conversionSoftware);

            globalNamespace.classes.AddRange(new[]
            {
                new TypeDeclaration
                {
                    name = "NullType"
                },
                new TypeDeclaration
                {
                    name   = "UndefinedType",
                    fields = new List <Field>
                    {
                        new Field
                        {
                            name      = "Undefined",
                            @readonly = true,
                            @static   = true,
                            template  = "undefined",
                            type      = new NamedType
                            {
                                Name = "UndefinedType"
                            }
                        }
                    }
                },
                new TypeDeclaration
                {
                    name       = "VoidType",
                    implements = new List <TypescriptParser.Type>
                    {
                        new NamedType {
                            Name = "UndefinedType"
                        }
                    }
                },
                new TypeDeclaration
                {
                    name    = "Symbol",
                    methods = new List <MethodOrDelegate>
                    {
                        new MethodOrDelegate
                        {
                            Arguments = new Arguments
                            {
                                Parameters = new List <Parameter>
                                {
                                    new Parameter
                                    {
                                        Name = "value",
                                        Type = new NamedType
                                        {
                                            Name = "string"
                                        }
                                    }
                                }
                            },
                            Name = "constructor"
                        },
                        new MethodOrDelegate
                        {
                            Name = "constructor"
                        }
                    }
                }
            });
            converter.globalNamespace = globalNamespace;
            //Console.WriteLine("Dotting...");
            //globalNamespace.ForeachTypeReference(v =>
            //{
            //    NamedType namedType = v as NamedType;
            //    if (string.IsNullOrEmpty(namedType?.Name))
            //        return;
            //    string[] dots = namedType.Name.Split('.');
            //    string[] preDots = new string[dots.Length - 1];
            //    Array.Copy(dots, preDots, dots.Length - 1);
            //    namedType.PreDots = preDots;
            //    namedType.Name = dots.Last();
            //});
            //Console.WriteLine("Merging...");
            //converter.MergeEnums(globalNamespace);
            //converter.RemoveAll(globalNamespace);
            Console.WriteLine("Referencing...");
            globalNamespace.ForeachTypeReference(converter.Reference);
            globalNamespace.ForeachType(v => converter.Reference(v.Type));
            Console.WriteLine("Unioning...");
            parser.Unions.ForEach(v =>
            {
                var typeA     = v.Generics.Generic[0] as NamedType;
                var typeB     = v.Generics.Generic[1] as NamedType;
                var typeDeclA = typeA.TypeDeclaration;
                var typeDeclB = typeB.TypeDeclaration;
                NamedType result;
                if (typeDeclA == null || typeDeclB == null)
                {
                    result = new NamedType
                    {
                        Name = "object"
                    }
                }
                ;
                else
                {
                    var shared = typeDeclA.FindSharedInterfaces(typeDeclB).Cast <TypescriptParser.Type>().ToList();
                    shared.Insert(0, new NamedType
                    {
                        Name     = "Union",
                        Generics = new Generics
                        {
                            Generic = new List <TypescriptParser.Type>
                            {
                                typeA, typeB
                            }
                        }
                    });
                    string name          = "Union_" + converter.Convert(typeA) + "_" + converter.Convert(typeB);
                    TypeDeclaration @ref = null;
                    globalNamespace.ForeachType(v2 => @ref = v2.name == name ? v2 : @ref);
                    bool create = @ref == null;
                    if (create)
                    {
                        @ref = new TypeDeclaration
                        {
                            name               = name,
                            implements         = shared,
                            IsUnion            = true,
                            GenericDeclaration = new GenericDeclaration
                            {
                                Generics = new List <string> {
                                    "A", "B"
                                }
                            }
                        }
                    }
                    ;
                    v.Name            = name;
                    v.TypeDeclaration = @ref;
                    if (create)
                    {
                        globalNamespace.classes.Add(@ref);
                    }
                }
            });
            Console.WriteLine("Renaming...");
            globalNamespace.ForeachType((Action <MethodOrDelegate>)(typeDeclaration =>
            {
                var delegatesFound = globalNamespace.FindType(new NamedType
                {
                    Name     = typeDeclaration.Name,
                    Generics = new Generics
                    {
                        Generic = typeDeclaration.GenericDeclaration.Generics.ConvertAll <TypescriptParser.Type>(v2 => new NamedType {
                            Name = v2
                        })
                    }
                }, converter.remove).delegatesFound;
                if (delegatesFound.Count > 1)
                {
                    typeDeclaration.Name += "_" + delegatesFound.Count;
                }
            }));
            Console.WriteLine("Removing duplicate fields...");
            converter.RemoveDuplicateFields();
            Console.WriteLine("Translating...");
            List <TypeDeclaration> toAdd = new List <TypeDeclaration>();

            globalNamespace.ForeachType(v => toAdd.AddRange(converter.Translate(v)));
            globalNamespace.ForeachType(v => converter.Cleanse(v.Type, v.GenericDeclaration, null));
            globalNamespace.classes.AddRange(toAdd);
            converter.remove.Clear();
            globalNamespace.ForeachType(converter.DeleteUnneededTypes);
            converter.RemoveAll(globalNamespace);
            Console.WriteLine("Writing C#...");
            //converter.ConvertUsingStatements(globalNamespace);
            converter.Result.Append(conversionSoftware == ConversionSoftware.Bridge ? "using Bridge;" : "using DuoCode.Runtime;");
            converter.Result.Append(
                @"
//using number = System.Double;
//using any = Bridge.Union<System.Delegate, object>;
//using boolean = System.Boolean;
#pragma warning disable CS0626
#pragma warning disable CS0824
//[assembly: Convention(Notation.LowerCamelCase)]
");
            converter.Convert(globalNamespace, false);
            Console.WriteLine("Writing...");
            File.WriteAllText($"{Path.GetFileNameWithoutExtension(location)}.cs", converter.Result.ToString());
            Console.WriteLine("Exiting...");
        }
 protected virtual void ExitNamedType(TContext context, NamedType namedType)
 {
 }
 protected bool Equals(NamedType other)
 {
     return string.Equals(Name, other.Name);
 }
Example #20
0
 public void HasVectorTypeBasedOnTheTypeOfItsItemExpressions()
 {
     Type("[0, 1, 2]").ShouldEqual(NamedType.Vector(Integer));
     Type("[true, false, true]").ShouldEqual(NamedType.Vector(Boolean));
 }
 public override object Visit(NamedType that, object value)
 {
     that.Reference.Visit(this, value);
     return null;
 }
Example #22
0
 public virtual object Visit(NamedType that, object value)
 {
     throw new System.NotImplementedException();
 }