예제 #1
0
        public static ITokenMatching HasLine(this ITokenMatching self, Func <IMatchedTokenMatching, ITokenMatching> inner)
        {
            if (!(self is IMatchedTokenMatching matchedTokenMatching))
            {
                return(self);
            }

            if (matchedTokenMatching.AllTokens.Count <= matchedTokenMatching.EndIndex)
            {
                return(TokenMatching <object> .MakeNotMatch(self.Context));
            }

            if (matchedTokenMatching.AllTokens[matchedTokenMatching.EndIndex].Is1(out var token) && token.SafeIs(out LineToken line))
            {
                if (inner(TokenMatching <object> .MakeStart(line.Tokens.Select(x => OrType.Make <IToken, ISetUp>(x)).ToList(), self.Context, 0)) is IMatchedTokenMatching)
                {
                    // uhhh new object?
                    // todo make a IMatchedTokenMatching with out a generic just for this
                    return(TokenMatching <object> .MakeMatch(matchedTokenMatching, new object(), matchedTokenMatching.EndIndex + 1));
                }
                ;
                return(TokenMatching <object> .MakeNotMatch(self.Context));
            }

            return(TokenMatching <object> .MakeNotMatch(self.Context));
        }
예제 #2
0
        public ITokenMatching <ISetUp <IBox <WeakTryAssignOperation>, Tpn.IValue> > TryMake(IMatchedTokenMatching tokenMatching)
        {
            var index = tokenMatching.EndIndex;

            if (tokenMatching.AllTokens.Count - 3 > index &&
                tokenMatching.AllTokens[index + 1].Is1(out var token) && token.SafeIs(out AtomicToken op) &&
                op.Item == SymbolsRegistry.TryAssignSymbol &&
                tokenMatching.AllTokens[index].Is2(out var lhs) &&
                tokenMatching.AllTokens[index + 2].Is2(out var rhs) &&
                tokenMatching.AllTokens[index + 3].Is2(out var rrhs))
            {
                var left  = OrType.Make <ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode>, IError>(lhs.SafeCastTo(out ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode> _));
                var right = OrType.Make <ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode>, IError>(rhs.SafeCastTo(out ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode> _));
                var block = OrType.Make <ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode>, IError>(rrhs.SafeCastTo(out ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode> _));


                var res = new TryAssignOperationPopulateScope(left, right, block);

                return(TokenMatching <ISetUp <IBox <WeakTryAssignOperation>, Tpn.IValue> > .MakeMatch(
                           tokenMatching,
                           res,
                           tokenMatching.EndIndex + 4
                           ));
            }

            return(TokenMatching <ISetUp <IBox <WeakTryAssignOperation>, Tpn.IValue> > .MakeNotMatch(
                       tokenMatching.Context));
        }
예제 #3
0
        public Nothing MethodDefinition(IInternalMethodDefinition co)
        {
            var name            = GenerateName();
            var typeBuilder     = moduleBuilder.DefineType(name);
            var constructor     = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new System.Type[] { });
            var myConstructorIL = constructor.GetILGenerator();

            myConstructorIL.Emit(OpCodes.Ldarg_0);
            myConstructorIL.Emit(OpCodes.Call, typeof(object).GetConstructors().First());
            myConstructorIL.Emit(OpCodes.Ret);

            var map = new Dictionary <IMemberDefinition, IOrType <FieldInfo, (FieldInfo funcField, FieldInfo path), EnclosedObjectMember> >();

            if (extensionLookup.methodLookup.TryGetValue(co, out var closure))
            {
                foreach (var member in closure.closureMember)
                {
                    PopulateMap(typeBuilder, map, member);
                }
            }

            realizedMethodLookup.Add(OrType.Make <IInternalMethodDefinition, IImplementationDefinition, IEntryPointDefinition>(co), new RealizedMethod(map, typeBuilder, constructor));

            Walk(co.Body, co);
            return(new Nothing());
        }
예제 #4
0
        public void OrTypesJustNeedBothToMatchOne()
        {
            var a1 = A1();
            var b1 = B1();
            var b2 = B2();
            var b3 = B3();

            var or1 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(Array.Empty <WeakMemberDefinition>()),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >());
            var or2 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b2)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b3)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(new List <WeakMemberDefinition> {
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("bm1"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(new NumberType()))),
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("bm2"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(new NumberType())))
            }),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >());

            // this works since both b2 and b3 are b1
            Assert.True(or1.TheyAreUs(or2, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
            // this does not work because niether b2 nor b3 are a1
            Assert.False(or2.TheyAreUs(or1, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
        }
예제 #5
0
 public IOrType <WeakObjectDefinition, WeakRootScope> Convert(Tpn.TypeSolution typeSolution, Tpn.TypeProblem2.Object from, IEnumerable <Tpn.ITypeProblemNode> context)
 {
     return(OrType.Make <WeakObjectDefinition, WeakRootScope>(new WeakRootScope(
                                                                  typeSolution.GetObjectType(from, context),
                                                                  assigns,
                                                                  entryPoint)));
 }
예제 #6
0
        public void Any()
        {
            var a1 = A1();
            var a2 = A2();
            var b1 = B1();
            var b2 = B2();
            var m1 = new MethodType(new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a2)), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)));
            var m2 = new MethodType(new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1)), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b2)));
            var t1 = new HasMembersType(new WeakScope(new List <WeakMemberDefinition> {
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("a"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1))),
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("b"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)))
            }));
            var t2 = new HasMembersType(new WeakScope(new List <WeakMemberDefinition> {
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("a"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a2))),
                new WeakMemberDefinition(Access.ReadWrite, new NameKey("b"), new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b2)))
            }));
            var or1 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(Array.Empty <WeakMemberDefinition>()),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >()
                );
            var or2 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(Array.Empty <WeakMemberDefinition>()),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >()
                );

            var any = new AnyType();

            Assert.All(new[] { a1, a2, b1, b2, m1, m2, t1, t2, or1, or2 }, x => any.TheyAreUs(x, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()));
        }
예제 #7
0
        //public static IOrType<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric> Broaden(this IOrType<MustHave, MustBePrimitive, GivenPathThen,  HasMembers, IsGenericRestraintFor, IsExternal> self) {
        //    return self.SwitchReturns(
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x),
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x),
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x),
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x),
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x),
        //        x => OrType.Make<MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x));
        //}

        public static IOrType <IIsPossibly <Guid>, IError> Primitive(this EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, HasMembers, IsGeneric, IsExternal> > self)
        {
            var primitives = self.SelectMany(x =>
            {
                if (x.Is2(out var v2))
                {
                    return(new[] { v2 });
                }
                return(Array.Empty <MustBePrimitive>());
            }).ToArray();

            if (primitives.Length == self.Count())
            {
                var groupedPrimitives = primitives.GroupBy(x => x.primitive).ToArray();
                if (groupedPrimitives.Length == 1)
                {
                    return(OrType.Make <IIsPossibly <Guid>, IError>(Possibly.Is(groupedPrimitives.First().Key)));
                }
                return(OrType.Make <IIsPossibly <Guid>, IError>(Error.Other("multiple primitives types...")));
            }

            if (primitives.Any())
            {
                return(OrType.Make <IIsPossibly <Guid>, IError>(Error.Other("primitives and non primitives")));
            }
            return(OrType.Make <IIsPossibly <Guid>, IError>(Possibly.IsNot <Guid>()));
        }
예제 #8
0
        public void OrTypesAreVarient()
        {
            var a1 = A1();
            var a2 = A2();
            var b1 = B1();
            var b2 = B2();

            var or1 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a1)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b1)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(Array.Empty <WeakMemberDefinition>()),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >()
                );
            var or2 = new FrontEndOrType(
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(a2)),
                new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(b2)),
                OrType.Make <IReadOnlyList <WeakMemberDefinition>, IError>(Array.Empty <WeakMemberDefinition>()),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >(),
                Possibly.IsNot <IBox <IOrType <IFrontendType <IVerifiableType>, IError> > >()
                );

            Assert.True(or1.TheyAreUs(or2, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
            Assert.False(or2.TheyAreUs(or1, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
        }
예제 #9
0
        public LastCallOperationMaker() : base(SymbolsRegistry.StaticLastCallSymbol, (l, r) => new Box <WeakLastCallOperation>(new WeakLastCallOperation(l, r)), (s, c, l, r) =>
        {
            // nearly duplicate code 3930174039475
            // you lazy shit extract this!
            var methodOr = l
                           .TransformInner(x => x.SetUpSideNode)
                           .TransformAndFlatten(x =>
                                                x.SafeIs(out Tpn.IValue value) ?
                                                OrType.Make <Tpn.IValue, IError>(value) :
                                                throw new NotImplementedException("left should be a value type, but I don't know where or how the error should happen"));

            var inputOr = r
                          .TransformInner(x => x.SetUpSideNode)
                          .TransformAndFlatten(x =>
                                               x.SafeIs(out Tpn.ICanAssignFromMe assignFrom) ?
                                               OrType.Make <Tpn.ICanAssignFromMe, IError>(assignFrom) :
                                               throw new NotImplementedException("right should be assignable from, but I don't know where or how the error should happen"));

            return(inputOr.SwitchReturns(
                       x => methodOr.SwitchReturns(
                           y => {
                s.Problem.IsAssignedTo(x, y.Input());
                return OrType.Make <Tpn.IValue, IError>(y.Returns());
            },
                           y => OrType.Make <Tpn.IValue, IError>(y)),
                       x => methodOr.SwitchReturns(
                           y => OrType.Make <Tpn.IValue, IError>(y.Returns()),
                           y => OrType.Make <Tpn.IValue, IError>(y))));
        }, true)
        {
        }
예제 #10
0
        // do these really need to be IBox? they seeme to generally be filled...
        // mayble IPossibly...
        public IBox <WeakObjectDefinition> Run(Tpn.TypeSolution context, IEnumerable <Tpn.ITypeProblemNode> stack)
        {
            var finalElements = nextElements.Select(x => x.SwitchReturns <IOrType <IBox <WeakAssignOperation>, IError> >(
                                                        y => {
                var res = y.Run(context, stack.Add(myScope)).GetValue();
                if (res is WeakAssignOperation weakAssign)
                {
                    return(OrType.Make <IBox <WeakAssignOperation>, IError>(new Box <WeakAssignOperation>(weakAssign)));
                }
                else
                {
                    return(OrType.Make <IBox <WeakAssignOperation>, IError>(Error.Other("lines in an object must me assignments")));
                }
            },
                                                        y => OrType.Make <IBox <WeakAssignOperation>, IError>(y))).ToArray();

            box.Fill(finalElements);

            var objectOr = myScope.Converter.Convert(context, myScope, stack);//;  context.GetObject(myScope);

            if (objectOr.Is1(out var v1))
            {
                return(new Box <WeakObjectDefinition>(v1));
            }
            throw new Exception("wrong or");
        }
예제 #11
0
        public ITokenMatching <ISetUp <IBox <WeakPathOperation>, Tpn.TypeProblem2.Member> > TryMake(IMatchedTokenMatching tokenMatching)
        {
            var matching = tokenMatching
                           .Has(new BinaryOperationMatcher(SymbolsRegistry.StaticPathSymbol), out (ISetUp lhs, ISetUp rhs)match);

            if (matching is IMatchedTokenMatching matched)
            {
                var left  = OrType.Make <ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode>, IError>(match.lhs.SafeCastTo(out ISetUp <IBox <IFrontendCodeElement>, Tpn.ITypeProblemNode> _));
                var right = OrType.Make <MemberPopulateScope, IError>(match.rhs.SafeCastTo(out MemberPopulateScope _));


                var res = new WeakPathOperationPopulateScope(left, right.TransformInner(x => x.memberName));

                //if (left.Is1(out var leftValue))
                //{
                //    tokenMatching.Context.Map.SetElementParent(leftValue, res);
                //}
                //if (right.Is1(out var rightValue))
                //{
                //    tokenMatching.Context.Map.SetElementParent(rightValue, res);
                //}

                return(TokenMatching <ISetUp <IBox <WeakPathOperation>, Tpn.TypeProblem2.Member> > .MakeMatch(
                           tokenMatching,
                           res,
                           matched.EndIndex));
            }

            return(TokenMatching <ISetUp <IBox <WeakPathOperation>, Tpn.TypeProblem2.Member> > .MakeNotMatch(
                       matching.Context));
        }
예제 #12
0
        public Nothing ImplementationDefinition(IImplementationDefinition codeElement)
        {
            var next = Push(codeElement);

            codeElement.ParameterDefinition.Convert(next);
            codeElement.ContextDefinition.Convert(next);
            if (codeElement.OutputType.SafeIs(out IInterfaceType type))
            {
                type.Convert(next);
            }

            foreach (var entry in codeElement.Scope.Members.Values.Select(x => x.Value).Except(new[] { codeElement.ParameterDefinition }))
            {
                lookup.AddLocal(OrType.Make <IEntryPointDefinition, IImplementationDefinition, IInternalMethodDefinition, IRootScope>(codeElement), entry);
            }

            lookup.AddArgument(OrType.Make <IImplementationDefinition, IInternalMethodDefinition, IEntryPointDefinition> (codeElement), codeElement.ParameterDefinition);
            lookup.AddField(OrType.Make <IEntryPointDefinition, IImplementationDefinition, IInternalMethodDefinition>(codeElement), codeElement.ContextDefinition);

            if (extensionLookup.implementationLookup.TryGetValue(codeElement, out var found))
            {
                foreach (var member in found.closureMember.Keys)
                {
                    lookup.AddField(OrType.Make <IEntryPointDefinition, IImplementationDefinition, IInternalMethodDefinition>(codeElement), member);
                }
            }

            next.Walk(codeElement.MethodBody);

            return(new Nothing());
        }
예제 #13
0
        public Nothing EntryPoint(IEntryPointDefinition entryPointDefinition)
        {
            if (entryPointDefinition.Scope.Members.Values.Any(x => x.Static))
            {
                throw new Exception("cant be static at this time");
            }


            var next = Push(entryPointDefinition);

            entryPointDefinition.ParameterDefinition.Convert(next);
            if (entryPointDefinition.OutputType.SafeIs(out IInterfaceType type))
            {
                type.Convert(next);
            }

            foreach (var entry in entryPointDefinition.Scope.Members.Values.Select(x => x.Value).Except(new[] { entryPointDefinition.ParameterDefinition }))
            {
                lookup.AddLocal(OrType.Make <IEntryPointDefinition, IImplementationDefinition, IInternalMethodDefinition, IRootScope>(entryPointDefinition), entry);
            }
            lookup.AddArgument(OrType.Make <IImplementationDefinition, IInternalMethodDefinition, IEntryPointDefinition>(entryPointDefinition), entryPointDefinition.ParameterDefinition);


            if (extensionLookup.entryPointLookup.TryGetValue(entryPointDefinition, out var found))
            {
                foreach (var member in found.closureMember.Keys)
                {
                    lookup.AddField(OrType.Make <IEntryPointDefinition, IImplementationDefinition, IInternalMethodDefinition>(entryPointDefinition), member);
                }
            }

            next.Walk(entryPointDefinition.Body);

            return(new Nothing());
        }
예제 #14
0
        public void InterestingCase2()
        {
            var member1Key      = new NameKey("x");
            var memeber1TypeBox = new Box <IOrType <IFrontendType <IVerifiableType>, IError> >();
            var member1         = new WeakMemberDefinition(Access.ReadWrite, member1Key, memeber1TypeBox);
            var type1           = new HasMembersType(new WeakScope(new List <WeakMemberDefinition> {
                member1
            }));

            memeber1TypeBox.Fill(OrType.Make <IFrontendType <IVerifiableType>, IError>(type1));

            var member2Key      = new NameKey("x");
            var memeber2TypeBox = new Box <IOrType <IFrontendType <IVerifiableType>, IError> >();
            var member2         = new WeakMemberDefinition(Access.ReadWrite, member2Key, memeber2TypeBox);
            var member3Key      = new NameKey("y");
            var member3         = new WeakMemberDefinition(Access.ReadWrite, member3Key, new Box <IOrType <IFrontendType <IVerifiableType>, IError> >(OrType.Make <IFrontendType <IVerifiableType>, IError>(new NumberType())));
            var type2           = new HasMembersType(new WeakScope(new List <WeakMemberDefinition> {
                member2, member3
            }));

            memeber2TypeBox.Fill(OrType.Make <IFrontendType <IVerifiableType>, IError>(type2));

            Assert.False(type1.TheyAreUs(type2, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
            Assert.False(type2.TheyAreUs(type1, new List <(IFrontendType <IVerifiableType>, IFrontendType <IVerifiableType>)>()).Is1OrThrow());
        }
예제 #15
0
 public IOrType <WeakBlockDefinition, WeakScope, WeakEntryPointDefinition> Convert(Tpn.TypeSolution typeSolution, Tpn.TypeProblem2.Scope from, IEnumerable <Tpn.ITypeProblemNode> context)
 {
     return(OrType.Make <WeakBlockDefinition, WeakScope, WeakEntryPointDefinition>(
                new WeakBlockDefinition(
                    body,
                    OrType.Make <WeakScope, IError>(typeSolution.GetWeakScope(from, context)),
                    Array.Empty <IIsPossibly <IFrontendCodeElement> >())));
 }
예제 #16
0
 public static IOrType <IFrontendType <IVerifiableType>, IError> UnwrapRefrence(this IFrontendType <IVerifiableType> frontendType)
 {
     if (frontendType is RefType refType)
     {
         return(refType.inner);
     }
     return(OrType.Make <IFrontendType <IVerifiableType>, IError>(frontendType));
 }
예제 #17
0
        public IOrType <IProject <TAssembly, TBacking>, IReadOnlyList <IError> > Parse <TAssembly, TBacking>(string text, IReadOnlyList <TAssembly> dependencies, string name)
            where TAssembly : IAssembly <TBacking>
        {
            var tokenizer = new Tokenizer(StaticSymbolsRegistry.SymbolsRegistry.Symbols.Except(new[] { SymbolsRegistry.StaticSubtractSymbol }).ToArray());
            var tokens    = tokenizer.Tokenize(text);

            var elementMatchingContest = new ElementMatchingContext();

            var scopePopulator = elementMatchingContest.ParseFile(tokens);

            var dependencyConverter = new DependencyConverter();

            var problem = new Tpn.TypeProblem2(new WeakScopeConverter(), scopePopulator, prob => {
                foreach (var dependency in dependencies)
                {
                    var type = prob.builder.CreateTypeExternalType(prob.Dependency, new WeakTypeDefinitionConverter(), dependency.Scope);

                    foreach (var memberPair in dependency.Scope.Members)
                    {
                        var innerType = ConvertType(prob.builder, type, OrType.Make <IVerifiableType, IError>(memberPair.Type));
                        innerType.Switch(x =>
                        {
                            prob.builder.CreatePublicMember(type, type, memberPair.Key, OrType.Make <IKey, IError>(x));
                        }, y =>
                        {
                            prob.builder.CreatePublicMember(type, memberPair.Key, y);
                        });
                    }
                    prob.builder.CreatePrivateMember(prob.Dependency, dependency.Key, OrType.Make <Tpn.TypeProblem2.MethodType, Tpn.TypeProblem2.Type, Tpn.TypeProblem2.Object, Tpn.TypeProblem2.OrType, Tpn.TypeProblem2.InferredType, Tpn.TypeProblem2.GenericTypeParameter, IError>(type));
                }
            });


            var populateScopeContex = new SetUpContext(problem.builder);
            var referanceResolver   = scopePopulator.Run(problem.ModuleRoot, populateScopeContex).Resolve;

            var solution = problem.Solve();

            var rootScope = referanceResolver.Run(solution, new List <Tpn.ITypeProblemNode>()
            {
                problem.Dependency,
                problem.ModuleRoot
            }).GetValue();

            var errors = rootScope.Validate().ToArray();

            if (errors.Any())
            {
                return(OrType.Make <IProject <TAssembly, TBacking>, IReadOnlyList <IError> >(errors));
            }

            var dependencyScope = problem.Dependency.Converter.Convert(solution, problem.Dependency, Array.Empty <Tpn.ITypeProblemNode>()).Is2OrThrow();


            var context = TransformerExtensions.NewConversionContext();

            return(OrType.Make <IProject <TAssembly, TBacking>, IReadOnlyList <IError> >(new Project <TAssembly, TBacking>(rootScope.Convert(context), dependencies, dependencyScope.Convert(context))));
        }
예제 #18
0
        public Nothing TypeDefinition(IInterfaceType codeElement)
        {
            foreach (var member in codeElement.Members)
            {
                lookup.TryAddTacField(OrType.Make <IObjectDefiniton, IInterfaceType, ITypeOr>(codeElement), member);
            }

            return(new Nothing());
        }
예제 #19
0
        // TODO these two method (TypeDefinition and TypeOr) don't make me feel good about the design
        // one is on the interface the other is not
        // I am using this weird switch (in MemberDefinition) to get to them
        // everywhere else I use polymorphism to get there

        public Nothing TypeOr(ITypeOr typeOr)
        {
            foreach (var member in typeOr.Members)
            {
                lookup.TryAddTacField(OrType.Make <IObjectDefiniton, IInterfaceType, ITypeOr>(typeOr), member);
            }

            return(new Nothing());
        }
예제 #20
0
 public ITokenMatching <ISetUp <IBox <IFrontendType <IVerifiableType> >, Tpn.TypeProblem2.TypeReference> > TryMake(IMatchedTokenMatching tokenMatching)
 {
     return(tokenMatching
            .Has(new KeyWordMaker("type"), out var _)
            .OptionalHas(new NameMaker(), out var typeName)
            .Has(new BodyMaker()).ConvertIfMatched(body => new TypeDefinitionPopulateScope(
                                                       tokenMatching.Context.ParseType(body),
                                                       typeName != default ? OrType.Make <NameKey, ImplicitKey>(new NameKey(typeName.Item)) : OrType.Make <NameKey, ImplicitKey>(new ImplicitKey(Guid.NewGuid()))), tokenMatching));
 }
예제 #21
0
 public static bool ExtendedIsCompatible(this IConstraint constraint, IOrType <MustHave, MustBePrimitive, GivenPathThen, HasMembers, IsGeneric, IsExternal> item)
 {
     return(item.SwitchReturns(
                x => constraint.IsCompatible(OrType.Make <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x), new List <UnorderedPair <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric> > >()),
                x => constraint.IsCompatible(OrType.Make <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x), new List <UnorderedPair <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric> > >()),
                x => constraint.IsCompatible(OrType.Make <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x), new List <UnorderedPair <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric> > >()),
                x => constraint.IsCompatible(OrType.Make <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric>(x), new List <UnorderedPair <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric> > >()),
                x => true,
                x => true));
 }
예제 #22
0
        public IReadOnlyList <IMemberDefinition> ObjectDefinition(IObjectDefiniton @object)
        {
            UpdateDefinedBy(@object.Scope, OrType.Make <IInternalMethodDefinition, IImplementationDefinition, IEntryPointDefinition, IBlockDefinition, IRootScope, IObjectDefiniton>(@object));

            var membersReferenced = Walk(@object.Assignments);

            return(membersReferenced
                   .Except(staticMembers)
                   .Except(@object.Scope.Members.Select(x => x.Value.Value)).ToArray());
        }
예제 #23
0
        public static IIsPossibly <IOrType <EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >, IError> > Input(this EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, HasMembers, IsGeneric, IsExternal> > self)
        {
            if (self.ErrorCheck(out var error))
            {
                return(Possibly.Is(OrType.Make <EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >, IError>(error)));
            }

            var mustHaves = self
                            .SelectMany(x =>
            {
                if (x.Is1(out var v1))
                {
                    return(new[] { v1 });
                }
                return(Array.Empty <MustHave>());
            })
                            .Where(x => x.path.Is2(out var _))
                            .ToArray();

            if (mustHaves.Any())
            {
                var set = new HashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >();

                var givenPaths = self
                                 .SelectMany(x =>
                {
                    if (x.Is3(out var v3))
                    {
                        return(new[] { v3 });
                    }
                    return(Array.Empty <GivenPathThen>());
                })
                                 .Where(x => x.path.Is2(out var _));

                foreach (var mustHave in mustHaves)
                {
                    foreach (var constraint in  mustHave.dependent.GetExtendedConstraints())
                    {
                        set.Add(constraint);
                    }
                }


                foreach (var givenPath in givenPaths)
                {
                    foreach (var constraint in givenPath.dependent.GetExtendedConstraints())
                    {
                        set.Add(constraint);
                    }
                }
                return(Possibly.Is(OrType.Make <EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >, IError>(new EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >(set))));
            }

            return(Possibly.IsNot <IOrType <EqualableHashSet <IOrType <MustHave, MustBePrimitive, GivenPathThen, OrConstraint, HasMembers, IsGeneric, IsExternal> >, IError> >());
        }
예제 #24
0
        public RootScopePopulateScope ParseFile(FileToken file)
        {
            IOrType <EntryPointDefinitionPopulateScope, IError> defaultEntryPoint = OrType.Make <EntryPointDefinitionPopulateScope, IError>(
                new EntryPointDefinitionPopulateScope(
                    new TypeReferancePopulateScope(new NameKey("empty")),
                    Array.Empty <IOrType <EntryPointDefinitionPopulateScope, IError> >(),
                    new TypeReferancePopulateScope(new NameKey("empty")),
                    "unused"));
            var entryToReturn = defaultEntryPoint;

            var assignments  = new List <IOrType <WeakAssignOperationPopulateScope, IError> >();
            var types        = new List <IOrType <TypeDefinitionPopulateScope, IError> >();
            var genericTypes = new List <IOrType <GenericTypeDefinitionPopulateScope, IError> >();

            foreach (var element in file.Tokens.Select(line => ParseLine(line.CastTo <LineToken>().Tokens)))
            {
                element.Switch(setup =>
                {
                    if (setup.SafeIs(out WeakAssignOperationPopulateScope assign))
                    {
                        assignments.Add(OrType.Make <WeakAssignOperationPopulateScope, IError>(assign));
                    }
                    else if (setup.SafeIs(out GenericTypeDefinitionPopulateScope genericType))
                    {
                        genericTypes.Add(OrType.Make <GenericTypeDefinitionPopulateScope, IError>(genericType));
                    }
                    else if (setup.SafeIs(out TypeDefinitionPopulateScope type))
                    {
                        types.Add(OrType.Make <TypeDefinitionPopulateScope, IError>(type));
                    }
                    else if (setup.SafeIs(out EntryPointDefinitionPopulateScope entry))
                    {
                        if (entryToReturn == defaultEntryPoint)
                        {
                            entryToReturn = OrType.Make <EntryPointDefinitionPopulateScope, IError>(entry);
                        }
                        else
                        {
                            entryToReturn = OrType.Make <EntryPointDefinitionPopulateScope, IError>(Error.Other("you can't have more than one entry point"));
                        }
                    }
                    else
                    {
                        assignments.Add(OrType.Make <WeakAssignOperationPopulateScope, IError>(Error.Other($"unexpected type {setup.GetType().Name}")));
                    }
                }
                               , error =>
                {
                    assignments.Add(OrType.Make <WeakAssignOperationPopulateScope, IError>(error));
                });
            }


            return(new RootScopePopulateScope(assignments.ToArray(), entryToReturn, types, genericTypes));
        }
예제 #25
0
 public IOrType <IFrontendType <IVerifiableType>, IError> Returns()
 {
     return(Right.TransformAndFlatten(x =>
     {
         if (x.GetValue() is IReturn @return)
         {
             return @return.Returns();
         }
         return OrType.Make <IFrontendType <IVerifiableType>, IError>(Error.Other($"{Right} should return"));
     }));
 }
예제 #26
0
        public static IOrType <IFrontendType <IVerifiableType>, IError> Returns(IOrType <IBox <IFrontendCodeElement>, IError> method)
        {
            return(method.ReturnsTypeOrErrors().TransformAndFlatten(thing => {
                if (thing is SyntaxModel.Elements.AtomicTypes.MethodType method)
                {
                    return method.OutputType.GetValue();
                }

                return OrType.Make <IFrontendType <IVerifiableType>, IError>(Error.Other($"{thing} should return"));
            }));
        }
예제 #27
0
파일: IError.cs 프로젝트: Prototypist1/Tac
 public static IOrType <TT, IError> CastToOr <T, TT>(this T self, IError error)
     where TT : T
 {
     if (self is TT tt)
     {
         return(OrType.Make <TT, IError>(tt));
     }
     else
     {
         return(OrType.Make <TT, IError>(error));
     }
 }
예제 #28
0
        public ITokenMatching <IKey> TryMake(IMatchedTokenMatching self)
        {
            var index = self.EndIndex;

            if (self.AllTokens.Count > index &&
                self.AllTokens[index].Is1(out var v1) && v1.SafeIs(out AtomicToken first) &&
                !double.TryParse(first.Item, out var _) &&
                IsNotKeyWord(first.Item))
            {
                {
                    var at = TokenMatching <NameKey> .MakeStart(self.AllTokens, self.Context, index + 1);

                    var match = new DefineGenericNMaker().TryMake(at);
                    if (match.SafeIs(out IMatchedTokenMatching <string[]> mathced))
                    {
                        var at2 = TokenMatching <NameKey> .MakeStart(self.AllTokens, self.Context, index + 2);

                        var match2 = new GenericNMaker().TryMake(at2);

                        if (match2.SafeIs(out IMatchedTokenMatching <IKey[]> mathced2))
                        {
                            return(TokenMatching <IKey> .MakeMatch(
                                       self,
                                       new DoubleGenericNameKey(
                                           new NameKey(first.Item),
                                           mathced.Value.Select(x => new NameKey(x)).ToArray(),
                                           mathced2.Value.Select(x => OrType.Make <IKey, IError>(x)).ToArray()),
                                       mathced2.EndIndex));
                        }
                    }
                }

                {
                    var at = TokenMatching <NameKey> .MakeStart(self.AllTokens, self.Context, index + 1);

                    var match = new GenericNMaker().TryMake(at);
                    if (match.SafeIs(out IMatchedTokenMatching <IKey[]> mathced))
                    {
                        return(TokenMatching <IKey> .MakeMatch(
                                   self,
                                   new GenericNameKey(
                                       new NameKey(first.Item),
                                       mathced.Value.Select(x => OrType.Make <IKey, IError>(x)).ToArray()),
                                   mathced.EndIndex));
                    }
                }

                return(TokenMatching <IKey> .MakeMatch(self, new NameKey(first.Item), index + 1));
            }

            return(TokenMatching <IKey> .MakeNotMatch(self.Context));
        }
예제 #29
0
        public IOrType <WeakMethodDefinition, WeakImplementationDefinition, WeakEntryPointDefinition, WeakGenericMethodDefinition> Convert(Tpn.TypeSolution typeSolution, Tpn.TypeProblem2.Method from, IEnumerable <Tpn.ITypeProblemNode> context)
        {
            var inputKey = from.PrivateMembers.Single(x => x.Value == from.Input.GetOrThrow());

            var scope = typeSolution.GetWeakScope(from, context);

            return(OrType.Make <WeakMethodDefinition, WeakImplementationDefinition, WeakEntryPointDefinition, WeakGenericMethodDefinition>(new WeakEntryPointDefinition(
                                                                                                                                               typeSolution.GetType(from.Returns.GetOrThrow(), context),
                                                                                                                                               scope.membersList.Single(x => x.Key.Equals(inputKey.Key)),
                                                                                                                                               body,
                                                                                                                                               OrType.Make <WeakScope, IError>(scope),
                                                                                                                                               Array.Empty <IIsPossibly <IConvertableFrontendCodeElement <ICodeElement> > >())));
        }
예제 #30
0
        public IReadOnlyList <IMemberDefinition> RootScope(IRootScope co)
        {
            UpdateDefinedBy(co.Scope, OrType.Make <IInternalMethodDefinition, IImplementationDefinition, IEntryPointDefinition, IBlockDefinition, IRootScope, IObjectDefiniton>(co));

            foreach (var item in co.Assignments)
            {
                item.Convert(this);
            }
            co.EntryPoint.Convert(this);

            // this can't have a closure
            return(Array.Empty <IMemberDefinition>());
        }
        /// <summary>
        /// Copy items to a destination folder and return the new ids for these items (Listing 5-14)
        /// </summary>
        /// <param name="binding">Exchange binding to use for the call</param>
        /// <param name="destinationFolderId">Destination for the items</param>
        /// <param name="itemsToCopy">Items to copy</param>
        /// <returns>List of new item ids</returns>
        /// 
        public List<ItemIdType> CopyItemEx(
                             BaseFolderIdType destinationFolderId,
                             List<BaseItemIdType> itemsToCopy)
        {
            // STEP 1:  First, we need to retrieve some unique information about
            // each item.  Let's use the PR_SEARCH_KEY. Note that extended properties are
            // discussed in Chapter 13, "Extended Properties"
            //
            GetItemType getSearchKeyRequest = new GetItemType();

            PathToExtendedFieldType searchKeyPath = new PathToExtendedFieldType();
            searchKeyPath.PropertyTag = "0x300B";
            searchKeyPath.PropertyType = MapiPropertyTypeType.Binary;

            // Use ItemResponseShapeType overload from chapter 3. We want the Id and the
            // search key
            //
            ItemResponseShapeType idAndSearchKeyShape = new ItemResponseShapeType(
                                     DefaultShapeNamesType.IdOnly,
                                     searchKeyPath);
            getSearchKeyRequest.ItemShape = idAndSearchKeyShape;
            getSearchKeyRequest.ItemIds = itemsToCopy.ToArray();

            // Get the items
            //
            GetItemResponseType getSearchKeyResponse =
                       this.GetItem(getSearchKeyRequest);
            List<string> base64SearchKeys = new List<string>(
                         getSearchKeyResponse.ResponseMessages.Items.Length);

            // For each item, add the search keys to our list
            //
            foreach (ItemInfoResponseMessageType searchKeyMessage in
                          getSearchKeyResponse.ResponseMessages.Items)
            {
                ExtendedPropertyType searchKeyProperty =
                        searchKeyMessage.Items.Items[0].ExtendedProperty[0];
                base64SearchKeys.Add((string)searchKeyProperty.Item);
            }

            // Now we have a list of the search keys for the items that we want to
            // copy.
            // STEP 2:  Perform the copy

            CopyItemType copyItemRequest = new CopyItemType();
            copyItemRequest.ToFolderId = new TargetFolderIdType();
            copyItemRequest.ToFolderId.Item = destinationFolderId;

            // just copy the array from our GetItem request rather than building a
            // new one.
            //
            copyItemRequest.ItemIds = getSearchKeyRequest.ItemIds;
            CopyItemResponseType copyResponse = this.CopyItem(copyItemRequest);

            // Now, we know that we do not get new ids from the above request, but
            // we (read: you) SHOULD check the response code for each of the copies
            // operations.
            //
            // STEP 3:  For each successful copy, we want to find the items by
            // search key.
            //
            FindItemType findBySearchKey = new FindItemType();
            findBySearchKey.ItemShape = idAndSearchKeyShape;
            findBySearchKey.ParentFolderIds = new BaseFolderIdType[] {
              destinationFolderId };
            findBySearchKey.Traversal = ItemQueryTraversalType.Shallow;
            findBySearchKey.Restriction = new RestrictionType();

            // Here we need to build up our query.  Rather than issuing several
            // FindItem calls, let's build up a single OR restriction here with a
            // bunch of items. Note that EWS restricts filter depths, so we
            // might need to break this up depending on how many items we are
            // copying...
            //
            if (base64SearchKeys.Count > 1)
            {
                OrType or = new OrType();
                List<IsEqualToType> orChildren = new List<IsEqualToType>();
                foreach (string searchKey in base64SearchKeys)
                {
                    // Note that CreateIsEqualToSearchKey is implemented on the partial class
                    // extension of RestrictionType.
                    //
                    IsEqualToType isEqualTo = RestrictionType.CreateIsEqualToSearchKey(
                          searchKeyPath, searchKey);
                    orChildren.Add(isEqualTo);
                }
                or.Items = orChildren.ToArray();

                findBySearchKey.Restriction.Item = or;
            }
            else
            {
                // we only have one item.  No need for the OR clause
                //
                IsEqualToType isEqualTo = RestrictionType.CreateIsEqualToSearchKey(
                                searchKeyPath, base64SearchKeys[0]);
                findBySearchKey.Restriction.Item = isEqualTo;
            }

            FindItemResponseType findResponse = this.FindItem(findBySearchKey);

            // Since we searched in a single target folder, we will have a single
            // response message
            //
            FindItemResponseMessageType findResponseMessage =
                findResponse.ResponseMessages.Items[0] as FindItemResponseMessageType;
            ItemType[] foundItems = (findResponseMessage.RootFolder.Item as
                                        ArrayOfRealItemsType).Items;
            List<ItemIdType> newIds = new List<ItemIdType>();
            foreach (ItemType item in foundItems)
            {
                newIds.Add(item.ItemId);
            }
            return newIds;
        }
            /// <summary>
            /// The process or.
            /// </summary>
            /// <param name="orType">
            /// The or type.
            /// </param>
            /// <param name="selections">
            /// The selections.
            /// </param>
            /// <exception cref="SdmxNotImplementedException">
            /// Key Family not supported in the IDataQuery.Or, please put in IDataQuery.And
            ///     -or-
            ///     Dataflow not supported in the IDataQuery.Or, please put in IDataQuery.And
            /// </exception>
            private void ProcessOr(OrType orType, ISet<IDataQuerySelection> selections)
            {
                if (orType != null)
                {
                    if (orType.Dimension != null)
                    {
                        foreach (DimensionType currentDimension in orType.Dimension)
                        {
                            AddComponentSelection(selections, currentDimension.id, currentDimension.TypedValue);
                        }
                    }

                    if (orType.Attribute != null)
                    {
                        foreach (AttributeType currentDimension in orType.Attribute)
                        {
                            AddComponentSelection(selections, currentDimension.id, currentDimension.TypedValue);
                        }
                    }

                    if (ObjectUtil.ValidCollection(orType.KeyFamily))
                    {
                        throw new SdmxNotImplementedException(
                            "Key Family not supported in the IDataQuery.Or, please put in IDataQuery.And");
                    }

                    if (ObjectUtil.ValidCollection(orType.Dataflow))
                    {
                        throw new SdmxNotImplementedException(
                            "Dataflow not supported in the IDataQuery.Or, please put in IDataQuery.And");
                    }

                    this.ProcessAnd(orType.And);
                }
            }