public void AddEmptyValidationErrors() { var errors = new ErrorCollection(); var actualEvents = errors.SubscribeObservableCollectionEvents(); errors.Add(ErrorCollection.EmptyValidationErrors); CollectionAssert.IsEmpty(actualEvents); CollectionAssert.IsEmpty(errors); }
/// <summary> /// Setup constructor /// </summary> /// <param name="parameters">Load parameters</param> /// <param name="errors">Error log</param> /// <param name="reader">XML reader positioned at the element that created this builder</param> public RootBuilder( ComponentLoadParameters parameters, ErrorCollection errors, XmlReader reader ) : base(parameters, errors, reader, null) { if ( reader.Name != "rb" ) { errors.Add( reader, "Expected root node of component XML document to be named <rb>, not <{0}>", reader.Name ); } BuildObject = parameters.Target ?? m_ChildObjects; }
public void AddWithTwo() { var errors = new ErrorCollection(); var changes = errors.SubscribeErrorCollectionEvents(); var actualEvents = errors.SubscribeObservableCollectionEvents(); var error1 = Factory.CreateValidationError(); var error2 = Factory.CreateValidationError(); errors.Add(Factory.CreateReadOnlyObservableCollection(error1, error2)); CollectionAssert.AreEqual(new[] { error1, error2 }, errors); CollectionAssert.AreEqual(Factory.ResetArgs(), actualEvents, ObservableCollectionArgsComparer.Default); CollectionAssert.AreEqual(new[] { Factory.CreateAddedEventArgs(error1, error2) }, changes, ErrorsChangedEventArgsComparer.Default); }
public void AddWithOne() { var reference = new ObservableCollection<ValidationError>(); var referenceEvents = reference.SubscribeObservableCollectionEvents(); var errors = new ErrorCollection(); var changes = errors.SubscribeErrorCollectionEvents(); var actualEvents = errors.SubscribeObservableCollectionEvents(); var error = Factory.CreateValidationError(); errors.Add(Factory.CreateReadOnlyObservableCollection(error)); reference.Add(error); CollectionAssert.AreEqual(reference, errors); CollectionAssert.AreEqual(referenceEvents, actualEvents, ObservableCollectionArgsComparer.Default); CollectionAssert.AreEqual(new[] { Factory.CreateAddedEventArgs(error) }, changes, ErrorsChangedEventArgsComparer.Default); }
public override void OutANamedType(ANamedType node) { if (node.Parent() is ATypedefDecl && ((ATypedefDecl)node.Parent()).GetName() == node) { return; } //Link named type to their definition (structs) List <ATypedefDecl> typeDefs = new List <ATypedefDecl>(); List <AStructDecl> structs = new List <AStructDecl>(); List <AMethodDecl> delegates = new List <AMethodDecl>(); List <TIdentifier> generics = new List <TIdentifier>(); bool matchPrimitive; GetMatchingTypes(node, typeDefs, structs, delegates, generics, out matchPrimitive); int matches = typeDefs.Count + structs.Count + delegates.Count + (matchPrimitive ? 1 : 0) + generics.Count; if (matches == 0) { errors.Add(new ErrorCollection.Error(node.GetToken(), "Could not find any types matching " + ((AAName)node.GetName()).AsString()), true); } else if (generics.Count != 1 && matches > 1) { List <ErrorCollection.Error> subError = new List <ErrorCollection.Error>(); if (matchPrimitive) { subError.Add(new ErrorCollection.Error(node.GetToken(), "Matches primitive " + ((AAName)node.GetName()).AsString())); } foreach (ATypedefDecl typeDef in typeDefs) { subError.Add(new ErrorCollection.Error(typeDef.GetToken(), "Matching typedef")); } foreach (AStructDecl structDecl in structs) { subError.Add(new ErrorCollection.Error(structDecl.GetName(), "Matching " + Util.GetTypeName(structDecl))); } foreach (AMethodDecl methodDecl in delegates) { subError.Add(new ErrorCollection.Error(methodDecl.GetName(), "Matching delegate")); } foreach (TIdentifier identifier in generics) { subError.Add(new ErrorCollection.Error(identifier, "Matching generic")); } errors.Add( new ErrorCollection.Error(node.GetToken(), "Found multiple types matching " + ((AAName)node.GetName()).AsString(), false, subError.ToArray()), true); } else { if (generics.Count == 1) { data.GenericLinks[node] = generics[0]; return; } if (typeDefs.Count == 1) { ATypedefDecl typeDef = typeDefs[0]; //data.TypeDefLinks[node] = typeDef; PType type = (PType)typeDef.GetType().Clone(); node.ReplaceBy(type); type.Apply(this); return; } if (structs.Count == 1) { data.StructTypeLinks[node] = structs[0]; } else if (delegates.Count == 1) { data.DelegateTypeLinks[node] = delegates[0]; } if (!matchPrimitive && !(structs.Count == 1 && data.Enums.ContainsKey(structs[0])) && node.Parent() is AEnrichmentDecl) //Not allowed to enrich a struct, class or delegate { errors.Add(new ErrorCollection.Error(node.GetToken(), "You can not enrich this type.")); } } }
/// <summary> /// Loads component XML from a stream /// </summary> public object Load( Stream stream, ISource source, LoadParameters parameters ) { if ( !( parameters is ComponentLoadParameters ) ) { ComponentLoadParameters newParameters = new ComponentLoadParameters( parameters.Target ); foreach ( IDynamicProperty property in parameters.Properties ) { newParameters.Properties.Add( property ); } parameters = newParameters; } parameters.CanCache = false; ErrorCollection errors = new ErrorCollection( string.Copy( source.Path ) ); XmlTextReader reader = new XmlTextReader( stream ); reader.WhitespaceHandling = WhitespaceHandling.Significant; try { if ( reader.MoveToContent( ) == XmlNodeType.None ) { AssetsLog.Warning( "XML component asset \"{0}\" was empty - returning null", source.Name ); return null; } } catch ( XmlException ex ) { AssetsLog.Error( "Moving to XML component asset \"{0}\" content threw an exception", source.Name ); Entry entry = new Entry( AssetsLog.GetSource( Severity.Error ), ex.Message ); Source.HandleEntry( entry.Locate( source.Path, ex.LineNumber, ex.LinePosition, "" ) ); throw new ApplicationException( string.Format( "Failed to load component XML asset \"{0}\" (see log for details)", source.Name ) ); } string cacheable = reader.GetAttribute( "cacheable" ); parameters.CanCache = ( cacheable != null ) && ( ( cacheable == "yes" ) || ( cacheable == "true" ) ); RootBuilder builder = ( RootBuilder )BaseBuilder.CreateBuilderFromReader( null, ( ComponentLoadParameters )parameters, errors, reader ); if ( errors.Count == 0 ) { BaseBuilder.SafePostCreate( builder ); if ( errors.Count == 0 ) { BaseBuilder.SafeResolve( builder, true ); } } if ( ( builder.BuildObject == null ) && ( errors.Count == 0 ) ) { errors.Add( builder, "Empty components file" ); } if ( errors.Count > 0 ) { foreach ( Entry error in errors ) { Source.HandleEntry( error ); } throw new ApplicationException( string.Format( "Failed to load component XML asset \"{0}\" (see log for details)", source.Name ) ); } // TODO: AP: bit dubious... if there's more than one object, return a list if ( builder.Children.Count == 0 ) { throw new ApplicationException( string.Format( "Failed to load component XML asset \"{0}\" - did not contain any components", source.Name ) ); } if ( builder.Children.Count == 1 ) { return builder.Children[ 0 ]; } return builder.Children; }
public string this[string propName] { get { String result = null; switch (propName) { case "IPAddress": { if (String.IsNullOrWhiteSpace(IPAddress)) { result = "IPAddress can't be empty"; } else { Regex ipAddrRegEx = new Regex(IPAddressRegEx); if (!(ipAddrRegEx.Match(IPAddress).Success)) { result = "Example: 127.0.0.1"; } } break; } case "UserName": { if (String.IsNullOrWhiteSpace(UserName)) { result = "User name can't be empty"; } else if (UserName.Length < 3) { result = "Min length is 3"; } else if (UserName.Length > 16) { result = "Max length is 16"; } else { Regex userNameRegEx = new Regex(UserNameRegEx); if (!(userNameRegEx.Match(UserName).Success)) { result = "User name can contain only Uppercase, Lowcase english symbols, digits, underscore and dash"; } } break; } case "Password": { if (String.IsNullOrWhiteSpace(Password)) { result = "Password can't be empty"; } else if (Password.Length < 6) { result = "Min length is 6"; } else if (Password.Length > 18) { result = "Max length is 18"; } else { Regex pswdRegEx = new Regex(Password); if (!(pswdRegEx.Match(Password).Success)) { result = "User name can contain only Uppercase, Lowcase english symbols, digits, underscore and dash"; } } break; } default: break; } if (ErrorCollection.ContainsKey(propName)) { ErrorCollection[propName] = result; } else if (result != null) { ErrorCollection.Add(propName, result); } RaisePropertyChangedEvent("ErrorCollection"); return(result); } }
internal void Finish(OidCollection applicationPolicy, OidCollection certificatePolicy) { WorkingChain workingChain = null; // If the chain had any errors during the previous build we need to walk it again with // the error collector running. if (Interop.Crypto.X509StoreCtxGetError(_storeCtx) != Interop.Crypto.X509VerifyStatusCode.X509_V_OK) { Interop.Crypto.X509StoreCtxReset(_storeCtx); workingChain = new WorkingChain(); Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback; Interop.Crypto.X509StoreCtxSetVerifyCallback(_storeCtx, workingCallback); bool verify = Interop.Crypto.X509VerifyCert(_storeCtx); if (workingChain.AbortedForSignatureError) { Debug.Assert(!verify, "verify should have returned false for signature error"); CloneChainForSignatureErrors(); // Reset to a WorkingChain that won't fail. workingChain = new WorkingChain(abortOnSignatureError: false); workingCallback = workingChain.VerifyCallback; Interop.Crypto.X509StoreCtxSetVerifyCallback(_storeCtx, workingCallback); verify = Interop.Crypto.X509VerifyCert(_storeCtx); } GC.KeepAlive(workingCallback); // Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the // chain is just fine (unless it returned a negative code for an exception) Debug.Assert(verify, "verify should have returned true"); const Interop.Crypto.X509VerifyStatusCode NoCrl = Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL; ErrorCollection?errors = workingChain.LastError > 0 ? (ErrorCollection?)workingChain[0] : null; if (_revocationMode == X509RevocationMode.Online && _remainingDownloadTime > TimeSpan.Zero && errors?.HasError(NoCrl) == true) { Interop.Crypto.X509VerifyStatusCode ocspStatus = CheckOcsp(); ref ErrorCollection refErrors = ref workingChain[0]; if (ocspStatus == Interop.Crypto.X509VerifyStatusCode.X509_V_OK) { refErrors.ClearError(NoCrl); } else if (ocspStatus != NoCrl) { refErrors.ClearError(NoCrl); refErrors.Add(ocspStatus); } } }
private int FoldInt(PExp exp, ref bool valid) { if (!valid) { return(-1); } if (exp is AIntConstExp) { return(int.Parse(((AIntConstExp)exp).GetIntegerLiteral().Text)); } if (exp is ABinopExp) { ABinopExp aExp = (ABinopExp)exp; int left = FoldInt(aExp.GetLeft(), ref valid); int right = FoldInt(aExp.GetLeft(), ref valid); if (!valid) { return(-1); } PBinop binop = aExp.GetBinop(); if (binop is APlusBinop) { return(left + right); } if (binop is AMinusBinop) { return(left - right); } if (binop is ATimesBinop) { return(left * right); } if ((binop is AModuloBinop || binop is ADivideBinop) && right == 0) { Token token = binop is AModuloBinop ? (Token)((AModuloBinop)binop).GetToken() : ((ADivideBinop)binop).GetToken(); errors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText57"))); throw new ParserException(null, null); } if (binop is AModuloBinop) { return(left % right); } if (binop is ADivideBinop) { return(left / right); } if (binop is AAndBinop) { return(left & right); } if (binop is AOrBinop) { return(left | right); } if (binop is AXorBinop) { return(left ^ right); } if (binop is ALBitShiftBinop) { return(left << right); } if (binop is ARBitShiftBinop) { return(left >> right); } } if (exp is ALvalueExp) { return(FoldInt(((ALvalueExp)exp).GetLvalue(), ref valid)); } valid = false; return(-1); }
public override void CaseAStructDecl(AStructDecl node) { if (checkedStructs.Contains(node)) { return; } checkedStructs.Add(node); //Set where they originate from. foreach (PLocalDecl localDecl in node.GetLocals()) { if (localDecl is AALocalDecl) { fieldOriginatesFrom[(AALocalDecl)localDecl] = node; } else //Is DeclLocalDecl { ADeclLocalDecl aLocalDecl = (ADeclLocalDecl)localDecl; PDecl decl = aLocalDecl.GetDecl(); if (decl is AMethodDecl) { methodOriginatesFrom[(AMethodDecl)decl] = node; } else if (decl is APropertyDecl) { propertyOriginatesFrom[(APropertyDecl)decl] = node; } else if (decl is AThisArrayPropertyDecl) { arrayPropertyOriginatesFrom[(AThisArrayPropertyDecl)decl] = node; } } } if (node.GetBase() == null) { return; } AStructDecl baseStr = Lookup((ANamedType)node.GetBase()); if (!checkedStructs.Contains(baseStr)) { CaseAStructDecl(baseStr); } CheckEnheritanceList(node, new List <AStructDecl>()); //A struct may not enhrit from a class if (node.GetClassToken() == null && baseStr.GetClassToken() != null) { errors.Add(new ErrorCollection.Error(node.GetName(), "A struct can not enherit from a class.", false, new ErrorCollection.Error(baseStr.GetName(), "Enherited class"))); } //Copy everything in base struct to here (Except from constructors) List <PLocalDecl> stuffToAdd = new List <PLocalDecl>(); foreach (AALocalDecl baseLocalVar in data.StructFields[baseStr]) { //Check that it is not overwritten foreach (AALocalDecl localVar in node.GetLocals().OfType <AALocalDecl>()) { if (baseLocalVar.GetName().Text == localVar.GetName().Text) { errors.Add(new ErrorCollection.Error(localVar.GetName(), "It is not possible to override fields.", false, new ErrorCollection.Error( fieldOriginatesFrom[baseLocalVar].GetName(), "Overridden " + Util.GetTypeName(fieldOriginatesFrom[baseLocalVar])))); throw new ParserException(null, null); } } foreach (APropertyDecl localProperty in data.StructProperties[node]) { if (localProperty.GetName().Text == baseLocalVar.GetName().Text) { errors.Add(new ErrorCollection.Error(localProperty.GetName(), "It is not possible to override fields.", false, new ErrorCollection.Error( fieldOriginatesFrom[baseLocalVar].GetName(), "Overridden " + Util.GetTypeName(fieldOriginatesFrom[baseLocalVar])))); throw new ParserException(null, null); } } //Insert at top AALocalDecl newLocalVar = (AALocalDecl)baseLocalVar.Clone(); baseLocalVar.Apply(new FixNamedRefferences(newLocalVar, data)); stuffToAdd.Add(newLocalVar); data.StructFields[node].Add(newLocalVar); fieldOriginatesFrom[newLocalVar] = fieldOriginatesFrom[baseLocalVar]; if (data.EnheritanceLocalMap.ContainsKey(baseLocalVar)) { data.EnheritanceLocalMap[newLocalVar] = data.EnheritanceLocalMap[baseLocalVar]; } else { data.EnheritanceLocalMap[newLocalVar] = baseLocalVar; } } for (int i = stuffToAdd.Count - 1; i >= 0; i--) { node.GetLocals().Insert(0, stuffToAdd[i]); } //Methods foreach (AMethodDecl baseMethod in data.StructMethods[baseStr]) { //Check that it is not overwritten foreach (AMethodDecl localMethod in node.GetLocals().OfType <ADeclLocalDecl>().Select(l => l.GetDecl()).OfType <AMethodDecl>()) { if (Util.GetMethodSignature(baseMethod) == Util.GetMethodSignature(localMethod)) { errors.Add(new ErrorCollection.Error(localMethod.GetName(), "It is not possible to override methods.", false, new ErrorCollection.Error( methodOriginatesFrom[baseMethod].GetName(), "Overridden " + Util.GetTypeName(methodOriginatesFrom[baseMethod])))); throw new ParserException(null, null); } } data.StructMethods[node].Add(baseMethod); } //Properties foreach (APropertyDecl baseProperty in data.StructProperties[baseStr]) { //Check that it is not overwritten foreach (APropertyDecl localProperty in data.StructProperties[node]) { if (localProperty.GetName().Text == baseProperty.GetName().Text) { errors.Add(new ErrorCollection.Error(localProperty.GetName(), "It is not possible to override properties.", false, new ErrorCollection.Error( propertyOriginatesFrom[baseProperty].GetName(), "Overridden " + Util.GetTypeName(propertyOriginatesFrom[baseProperty])))); throw new ParserException(null, null); } } foreach (AALocalDecl localVar in node.GetLocals().OfType <AALocalDecl>()) { if (baseProperty.GetName().Text == localVar.GetName().Text) { errors.Add(new ErrorCollection.Error(localVar.GetName(), "It is not possible to override properties.", false, new ErrorCollection.Error( propertyOriginatesFrom[baseProperty].GetName(), "Overridden " + Util.GetTypeName(propertyOriginatesFrom[baseProperty])))); throw new ParserException(null, null); } } data.StructProperties[node].Add(baseProperty); } }
public string this[string propertyname] { get { string result = null; switch (propertyname) { case "EntityNameTxt": if (string.IsNullOrWhiteSpace(EntityNameTxt)) { result = "Entity Name cannot be empty"; } else if (IsBeginWNum(EntityNameTxt)) { result = "Cannot begin with a number"; } else if (IsValidName(EntityNameTxt)) { result = "Not a valid name. Only Letters, Numbers or underscore are allowed"; } else if (IsReservedWord(EntityNameTxt)) { result = "This is a Reserved Word"; } break; case "PortNameTxt": if (string.IsNullOrWhiteSpace(PortNameTxt)) { result = "Port Name cannot be empty"; } else if (IsBeginWNum(PortNameTxt)) { result = "Cannot begin with a number"; } else if (IsValidName(PortNameTxt)) { result = "Not a valid name. Only Letters, Numbers or underscore are allowed"; } else if (IsReservedWord(PortNameTxt)) { result = "This is a Reserved Word"; } else if (PNameExist(PortNameTxt)) { result = "Port Name Exists"; } break; case "DirectionSel": if (!IsDirectionSel(DirectionSel)) { result = "No Direction Selected"; } break; case "MsbTxt": if (BitsEnable == true) { if (string.IsNullOrWhiteSpace(MsbTxt)) { result = "MSB cannot be empty"; } else if (IsInterger(MsbTxt)) { result = "Only Integers are allowed"; } break; } else { break; } case "LsbTxt": if (BitsEnable == true) { if (string.IsNullOrWhiteSpace(LsbTxt)) { result = "LSB cannot be empty"; } else if (IsInterger(LsbTxt)) { result = "Only Integers are allowed"; } break; } else { break; } } if (ErrorCollection.ContainsKey(propertyname)) { ErrorCollection[propertyname] = result; } else if (result != null) { ErrorCollection.Add(propertyname, result); } OnPropertyChanged("ErrorCollection"); OnPropertyChanged("FinishEnable"); OnPropertyChanged("AddPortEnable"); return(result); } }
public string this[string name] { get { string errorText = null; //a line of text that show when validate switch (name) { case "StudentId": if (string.IsNullOrWhiteSpace(StudentId)) { errorText = "Student ID cannot be empty"; } else if (StudentId.ToString().Length > 10) { errorText = "Student ID maximun length is 10 charaters"; } else if (!Regex.Match(StudentId, @"^[0-9]+$").Success) { errorText = "Invalid Student ID"; } break; case "FirstName": if (string.IsNullOrWhiteSpace(FirstName)) { errorText = "First Name cannot be empty"; } else if (FirstName.Length > 20) { errorText = "First Name maximun length is 20 charaters"; } else if (!Regex.Match(FirstName, @"^[a-zA-Z]+$").Success) { errorText = "Invalid First Name"; } break; case "LastName": if (string.IsNullOrWhiteSpace(LastName)) { errorText = "Last Name cannot be empty"; } else if (LastName.Length > 20) { errorText = "Last Name maximun length is 20 charaters"; } else if (!Regex.Match(LastName, @"^[a-zA-Z]+$").Success) { errorText = "Invalid Last Name"; } break; case "BirthDate": break; case "Gender": break; case "City": if (string.IsNullOrWhiteSpace(City)) { errorText = "City cannot be empty"; } else if (City.Length > 20) { errorText = "City maximun length is 20 charaters"; } else if (!Regex.Match(City, @"^[a-zA-Z]+$").Success) { errorText = "Invalid City"; } break; case "Email": var regex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z"; if (string.IsNullOrWhiteSpace(Email)) { errorText = "Email cannot be empty"; } else if (!Regex.Match(Email, regex).Success) { errorText = "Email is invalid"; } else if (Email.ToString().Length > 30) { errorText = "Email maximun length is 30 charaters"; } break; case "Class": if (string.IsNullOrWhiteSpace(Class)) { errorText = "Class cannot be empty"; } break; } if (ErrorCollection.ContainsKey(name)) { ErrorCollection[name] = errorText; } else if (errorText != null) { ErrorCollection.Add(name, errorText); } NotifyOfPropertyChange(() => ErrorCollection); NotifyOfPropertyChange(() => CanSaveButton); return(errorText); } }
public static void GetTargets(string name, Token node, Node reciever, //Either null, AAName, or PExp PType returnType, //Either null, or Some type the method return type must be assignable to List<PType> argTypes, List<AMethodDecl> candidates, out bool matchArrayResize, List<AMethodDecl> implicitCandidates, List<AMethodDecl> matchingNames, out PExp baseExp, List<AMethodDecl> matchingDelegates, SharedData data, ErrorCollection errors ) { baseExp = null; matchArrayResize = false; if (reciever == null) {//A simple invoke //Look in current struct //Look in all visible namespaces //Look in library methods AStructDecl currentStruct = Util.GetAncestor<AStructDecl>(node); if (currentStruct != null) { foreach (AMethodDecl methodDecl in data.StructMethods[currentStruct]) { if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && Util.GetAncestor<AStructDecl>(methodDecl) != currentStruct) continue; if (methodDecl.GetVisibilityModifier() is AProtectedVisibilityModifier && !Util.Extends(Util.GetAncestor<AStructDecl>(methodDecl), currentStruct, data)) continue; if (methodDecl.GetStatic() == null && Util.IsStaticContext(node)) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int i = 0; i < argTypes.Count; i++) { PType argType = argTypes[i]; AALocalDecl formal = (AALocalDecl) methodDecl.GetFormals()[i]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0) {//Set base exp if (methodDecl.GetStatic() != null) { //Calling static method baseExp = null; } else if (currentStruct.GetClassToken() != null || Util.HasAncestor<AConstructorDecl>(node) || Util.HasAncestor<ADeconstructorDecl>(node)) {//Dynamic context baseExp = new ALvalueExp(new APointerLvalue(new TStar("*"), new ALvalueExp(new AThisLvalue(new TThis("this"))))); } else {//Struct method to struct method baseExp = null; } } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } if (candidates.Count + implicitCandidates.Count == 0) { //Global methods List<IList> visibleDecls = Util.GetVisibleDecls(node, true); AASourceFile currentFile = Util.GetAncestor<AASourceFile>(node); List<string> currentNamespace = Util.GetFullNamespace(node); foreach (IList declList in visibleDecls) { bool isSameFile = false; bool isSameNamespace = false; if (declList.Count > 0) { isSameFile = currentFile == Util.GetAncestor<AASourceFile>((PDecl) declList[0]); isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace((PDecl) declList[0])); } foreach (PDecl decl in declList) { if (decl is AMethodDecl) { AMethodDecl methodDecl = (AMethodDecl) decl; if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && !isSameNamespace) continue; if (methodDecl.GetStatic() != null && !isSameFile) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int i = 0; i < argTypes.Count; i++) { PType argType = argTypes[i]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[i]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } } //Library methods foreach (AMethodDecl methodDecl in data.Libraries.Methods) { if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility //Okay, the library doesn't have any private methods. But hey. if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && currentNamespace.Count > 0) continue; if (methodDecl.GetStatic() != null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int i = 0; i < argTypes.Count; i++) { PType argType = argTypes[i]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[i]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } } else if (reciever is AAName) {//Lookup possibilities for reciever List<List<Node>>[] targets; List<ANamespaceDecl> namespaces = new List<ANamespaceDecl>(); bool reportedError; TypeLinking.GetTargets((AAName)reciever, out targets, namespaces, data, errors, out reportedError); if (reportedError) throw new ParserException(node, "TypeChecking.GetTargets"); AStructDecl currentStruct = Util.GetAncestor<AStructDecl>(node); int iteration; for (iteration = 0; iteration < targets.Length; iteration++) { List<Node> matchingList = null; foreach (List<Node> list in targets[iteration]) { Node last = list[list.Count - 1]; PType type = null; if (last is AALocalDecl) { type = ((AALocalDecl) last).GetType(); } else if (last is APropertyDecl) { type = ((APropertyDecl) last).GetType(); } else if (last is AFieldDecl) { type = ((AFieldDecl) last).GetType(); } else if (last is TIdentifier) { type = new ANamedType(new TIdentifier("int"), null); } if (last is AStructDecl) { //Special. Static only AStructDecl structDecl = ((AStructDecl)last); foreach (AMethodDecl methodDecl in data.StructMethods[structDecl]) { if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && Util.GetAncestor<AStructDecl>(methodDecl) != currentStruct) continue; if (methodDecl.GetVisibilityModifier() is AProtectedVisibilityModifier && !Util.Extends(Util.GetAncestor<AStructDecl>(methodDecl), currentStruct, data)) continue; if (methodDecl.GetStatic() == null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0) {//Set base exp //Calling static method baseExp = null; } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } else { //Find methods based on baseType if (type is ANamedType && data.StructTypeLinks.ContainsKey((ANamedType) type) && !(data.Enums.ContainsKey(data.StructTypeLinks[(ANamedType) type]))) { //Non static only AStructDecl structDecl = data.StructTypeLinks[(ANamedType) type]; foreach (AMethodDecl methodDecl in data.StructMethods[structDecl]) { if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && Util.GetAncestor<AStructDecl>(methodDecl) != currentStruct) continue; if (methodDecl.GetVisibilityModifier() is AProtectedVisibilityModifier && !Util.Extends(Util.GetAncestor<AStructDecl>(methodDecl), currentStruct, data)) continue; if (methodDecl.GetStatic() != null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0 && implicitCandidates.Count == 0) {//Set base exp baseExp = new ALvalueExp(TypeLinking.Link((AAName) reciever, node, list, data)); } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } else if (type is ANamedType && data.DelegateTypeLinks.ContainsKey((ANamedType)type)) { if (matchingDelegates != null && name == "Invoke") { AMethodDecl delegateDecl = data.DelegateTypeLinks[(ANamedType) type]; if (delegateDecl.GetFormals().Count == argTypes.Count) { matchingNames.Add(delegateDecl); //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(delegateDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)delegateDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; matchingDelegates.Add(delegateDecl); if (candidates.Count == 0 && implicitCandidates.Count == 0) {//Set base exp baseExp = new ALvalueExp(TypeLinking.Link((AAName)reciever, node, list, data)); } if (add) candidates.Add(delegateDecl); if (matchImplicit) implicitCandidates.Add(delegateDecl); } } } else { //Look for enrichments List<IList> visibleDecls = Util.GetVisibleDecls(node, true); AEnrichmentDecl currentEnrichment = Util.GetAncestor<AEnrichmentDecl>(node); foreach (IList declList in visibleDecls) { foreach (PDecl decl in declList) { if (decl is AEnrichmentDecl) { AEnrichmentDecl enrichment = (AEnrichmentDecl) decl; if (!Util.TypesEqual(type, enrichment.GetType(), data)) continue; foreach (PDecl enrichmentDecl in enrichment.GetDecl()) { if (enrichmentDecl is AMethodDecl) { AMethodDecl methodDecl = (AMethodDecl) enrichmentDecl; if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && enrichment != currentEnrichment) continue; if (methodDecl.GetStatic() != null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0 && implicitCandidates.Count == 0) {//Set base exp baseExp = new ALvalueExp(TypeLinking.Link((AAName)reciever, node, list, data)); } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } } } } } } } if (candidates.Count + implicitCandidates.Count > 0) break; } if (iteration >= 2) {//The search continued to global variables. Look in namespaces as well AASourceFile currentFile = Util.GetAncestor<AASourceFile>(node); List<string> currentNamespace = Util.GetFullNamespace(node); foreach (ANamespaceDecl namespaceDecl in namespaces) { bool isSameFile = Util.GetAncestor<AASourceFile>(namespaceDecl) == currentFile; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(namespaceDecl)); foreach (PDecl decl in namespaceDecl.GetDecl()) { if (decl is AMethodDecl) { AMethodDecl methodDecl = (AMethodDecl) decl; if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && !isSameNamespace) continue; if (methodDecl.GetStatic() != null && !isSameFile) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int i = 0; i < argTypes.Count; i++) { PType argType = argTypes[i]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[i]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } } } } else {//Get base type from exp, and find matching enrichment/struct PType type = data.ExpTypes[(PExp) reciever]; if (type is ADynamicArrayType && name == "Resize" && argTypes.Count == 1 && Assignable(argTypes[0], new ANamedType(new TIdentifier("int"), null))) { matchArrayResize = true; baseExp = (PExp) reciever; } AStructDecl currentStruct = Util.GetAncestor<AStructDecl>(node); if (type is ANamedType && data.StructTypeLinks.ContainsKey((ANamedType)type)) { //Non static only AStructDecl structDecl = data.StructTypeLinks[(ANamedType)type]; foreach (AMethodDecl methodDecl in data.StructMethods[structDecl]) { if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && Util.GetAncestor<AStructDecl>(methodDecl) != currentStruct) continue; if (methodDecl.GetVisibilityModifier() is AProtectedVisibilityModifier && !Util.Extends(Util.GetAncestor<AStructDecl>(methodDecl), currentStruct, data)) continue; if (methodDecl.GetStatic() != null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0 && implicitCandidates.Count == 0) {//Set base exp baseExp = (PExp)reciever; } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } else if (type is ANamedType && data.DelegateTypeLinks.ContainsKey((ANamedType)type)) { if (matchingDelegates != null && name == "Invoke") { AMethodDecl delegateDecl = data.DelegateTypeLinks[(ANamedType)type]; if (delegateDecl.GetFormals().Count == argTypes.Count) { matchingNames.Add(delegateDecl); //Check return type if (!(returnType != null && !(returnType is AVoidType) && !Assignable(delegateDecl.GetReturnType(), returnType))) { //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl) delegateDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (add || matchImplicit) { matchingDelegates.Add(delegateDecl); if (candidates.Count == 0 && implicitCandidates.Count == 0) { //Set base exp baseExp = (PExp)reciever; } if (add) candidates.Add(delegateDecl); if (matchImplicit) implicitCandidates.Add(delegateDecl); } } } } } else { //Look for enrichments List<IList> visibleDecls = Util.GetVisibleDecls(node, true); AEnrichmentDecl currentEnrichment = Util.GetAncestor<AEnrichmentDecl>(node); foreach (IList declList in visibleDecls) { foreach (PDecl decl in declList) { if (decl is AEnrichmentDecl) { AEnrichmentDecl enrichment = (AEnrichmentDecl)decl; if (!Util.TypesEqual(type, enrichment.GetType(), data)) continue; foreach (PDecl enrichmentDecl in enrichment.GetDecl()) { if (enrichmentDecl is AMethodDecl) { AMethodDecl methodDecl = (AMethodDecl)enrichmentDecl; if (methodDecl.GetName().Text == name && methodDecl.GetFormals().Count == argTypes.Count && methodDecl.GetDelegate() == null) { matchingNames.Add(methodDecl); //Visibility if (methodDecl.GetVisibilityModifier() is APrivateVisibilityModifier && enrichment != currentEnrichment) continue; if (methodDecl.GetStatic() != null) continue; //Check return type if (returnType != null && !(returnType is AVoidType) && !Assignable(methodDecl.GetReturnType(), returnType)) continue; //Check that parameters are assignable bool add = true; bool matchImplicit = false; for (int j = 0; j < argTypes.Count; j++) { PType argType = argTypes[j]; AALocalDecl formal = (AALocalDecl)methodDecl.GetFormals()[j]; PType formalType = formal.GetType(); if (formal.GetOut() != null && !Assignable(formalType, argType) || formal.GetRef() != null && !(Assignable(argType, formalType) && Assignable(formalType, argType)) || formal.GetOut() == null && formal.GetRef() == null && !Assignable(argType, formalType)) { add = false; if (formal.GetOut() == null && formal.GetRef() == null && ImplicitAssignable(argType, formalType)) { matchImplicit = true; } else { matchImplicit = false; break; } } } if (!add && !matchImplicit) continue; if (candidates.Count == 0 && implicitCandidates.Count == 0) {//Set base exp baseExp = (PExp)reciever; } if (add) candidates.Add(methodDecl); if (matchImplicit) implicitCandidates.Add(methodDecl); } } } } } } } } int candidateCount = candidates.Count + (matchArrayResize ? 1 : 0); if (candidateCount + implicitCandidates.Count == 0 && !matchArrayResize) { List<ErrorCollection.Error> subErrors = new List<ErrorCollection.Error>(); foreach (AMethodDecl matchingName in matchingNames) { subErrors.Add(new ErrorCollection.Error(matchingName.GetName(), LocRM.GetString("ErrorText124"))); } errors.Add(new ErrorCollection.Error(node, LocRM.GetString("ErrorText125"), false, subErrors.ToArray())); throw new ParserException(node, "TypeChecking.GetTargets"); } if (candidateCount > 1) { List<ErrorCollection.Error> subErrors = new List<ErrorCollection.Error>(); foreach (AMethodDecl matchingName in candidates) { subErrors.Add(new ErrorCollection.Error(matchingName.GetName(), LocRM.GetString("ErrorText38"))); } if (matchArrayResize) subErrors.Add(new ErrorCollection.Error(node, LocRM.GetString("ErrorText126"))); errors.Add(new ErrorCollection.Error(node, LocRM.GetString("ErrorText127"), false, subErrors.ToArray())); throw new ParserException(node, "TypeChecking.GetTargets"); } if (candidateCount == 0 && implicitCandidates.Count > 1) { List<ErrorCollection.Error> subErrors = new List<ErrorCollection.Error>(); foreach (AMethodDecl matchingName in implicitCandidates) { subErrors.Add(new ErrorCollection.Error(matchingName.GetName(), LocRM.GetString("ErrorText38"))); } errors.Add(new ErrorCollection.Error(node, LocRM.GetString("ErrorText128"), false, subErrors.ToArray())); throw new ParserException(node, "TypeChecking.GetTargets"); } }
private static void GetTargets(AAName node, List<string> names, out List<List<Node>>[] targets, List<ANamespaceDecl> namespaces, SharedData data, ErrorCollection errors, out bool reportedError, bool first = false) { targets = new [] { new List<List<Node>>(),//0: Stuff starting with a local variable new List<List<Node>>(),//1: Stuff starting with a struct field/property new List<List<Node>>() //2: Stuff starting with a global declaration }; reportedError = false; string name = names[names.Count - 1]; if (names.Count == 1) { //Locals AConstructorDecl pConstructor = Util.GetAncestor<AConstructorDecl>(node); AMethodDecl pMethod = Util.GetAncestor<AMethodDecl>(node); AABlock pBlock = Util.GetAncestor<AABlock>(node); if (pBlock != null) { if (data.Locals.ContainsKey(pBlock)) { foreach (AALocalDecl local in data.Locals[pBlock]) { if (local.GetName().Text == name && Util.IsBefore(local, node)) targets[0].Add(new List<Node>(){local}); } } } else if (pConstructor != null) { foreach (AALocalDecl formal in pConstructor.GetFormals()) { if (formal.GetName().Text == name) targets[0].Add(new List<Node>(){formal}); } } //Fields/properties in current struct AStructDecl currentStruct = Util.GetAncestor<AStructDecl>(node); if (currentStruct != null) { bool isStaticContext = false; if (Util.HasAncestor<AMethodDecl>(node)) isStaticContext = Util.GetAncestor<AMethodDecl>(node).GetStatic() != null; else if (Util.HasAncestor<APropertyDecl>(node)) isStaticContext = Util.GetAncestor<APropertyDecl>(node).GetStatic() != null; else if (Util.HasAncestor<AALocalDecl>(node)) isStaticContext = Util.GetAncestor<AALocalDecl>(node).GetStatic() != null; foreach (AALocalDecl local in data.StructFields[currentStruct]) { if (local.GetName().Text != name) continue; //If it's an enherited private variable, you can't refer to it. if (local.GetVisibilityModifier() is APrivateVisibilityModifier && data.EnheritanceLocalMap.ContainsKey(local)) { continue; } if (local.GetStatic() != null) { //Add it to the dotted map targets[1].Add(new List<Node>(){currentStruct, local}); continue; } if (isStaticContext) continue;//Can't refference non static stuff from static context targets[1].Add(new List<Node>(){local}); } foreach (APropertyDecl local in data.StructProperties[currentStruct]) { if (local.GetName().Text != name) continue; //If it's an enherited private variable, you can't refer to it. if (local.GetVisibilityModifier() is APrivateVisibilityModifier && Util.GetAncestor<AStructDecl>(local) != currentStruct) { continue; } if (local.GetStatic() != null) { //Add it to the dotted map targets[1].Add(new List<Node>() { currentStruct, local }); continue; } if (isStaticContext) continue;//Can't refference non static stuff from static context targets[1].Add(new List<Node>(){local}); } } //Global field/property List<IList> visibleDecls = Util.GetVisibleDecls(node, true); AASourceFile currentFile = Util.GetAncestor<AASourceFile>(node); List<string> currentNamespace = Util.GetFullNamespace(node); foreach (IList declList in visibleDecls) { bool isSameFile = false; if (declList.Count > 0) isSameFile = currentFile == Util.GetAncestor<AASourceFile>((PDecl) declList[0]); foreach (PDecl decl in declList) { if (decl is AFieldDecl) { AFieldDecl aDecl = (AFieldDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !isSameFile && aDecl.GetStatic() != null) continue; targets[2].Add(new List<Node>(){decl}); } else if (decl is APropertyDecl) { APropertyDecl aDecl = (APropertyDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !isSameFile && aDecl.GetStatic() != null) continue; targets[2].Add(new List<Node>() { decl }); } else if (decl is AStructDecl && !first) { AStructDecl aDecl = (AStructDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier) continue; targets[2].Add(new List<Node>() { decl }); } } } //Look in lib fields foreach (AFieldDecl field in data.Libraries.Fields) { if (field.GetName().Text == name) { targets[2].Add(new List<Node>() { field }); } } //Namespaces visibleDecls = Util.GetVisibleDecls(node, false); foreach (IList declList in visibleDecls) { foreach (PDecl decl in declList) { if (decl is ANamespaceDecl) { ANamespaceDecl aDecl = (ANamespaceDecl)decl; if (aDecl.GetName().Text != name) continue; namespaces.Add(aDecl); } } } } else { /*private static void GetTargets(AAName node, List<string> names, List<AALocalDecl> locals, List<Node> structDecls, //<AAlocaldecl/APropertyDecl> List<PDecl> globalDecls, List<AStructDecl> structType, List<List<Node>> dotted, //<any of the above>.<AAlocaldecl/APropertyDecl> List<ANamespaceDecl> namespaces, SharedData data, ErrorCollection errors, out bool reportedError)*/ List<string> baseNames = new List<string>(); baseNames.AddRange(names); baseNames.RemoveAt(baseNames.Count - 1); List<List<Node>>[] baseTargets; List<ANamespaceDecl> baseNamespaces = new List<ANamespaceDecl>(); GetTargets(node, baseNames, out baseTargets, baseNamespaces, data, errors, out reportedError); AStructDecl currentStruct = Util.GetAncestor<AStructDecl>(node); for (int i = 0; i < baseTargets.Length; i++) { foreach (List<Node> list in baseTargets[i]) { Node last = list[list.Count - 1]; PType type = null; if (last is AALocalDecl) { type = ((AALocalDecl) last).GetType(); } else if (last is APropertyDecl) { type = ((APropertyDecl) last).GetType(); } else if (last is AFieldDecl) { type = ((AFieldDecl) last).GetType(); } else if (last is TIdentifier) { type = new ANamedType(new TIdentifier("int"), null); } if (last is AStructDecl) { //Special. Static only AStructDecl structDecl = ((AStructDecl) last); foreach (AALocalDecl local in data.StructFields[structDecl]) { if (local.GetName().Text != name) continue; //Must be public if we are outside the struct //If it's an enherited private variable, you can't refer to it. if (currentStruct != structDecl && !(local.GetVisibilityModifier() is APublicVisibilityModifier) || currentStruct == structDecl && local.GetVisibilityModifier() is APrivateVisibilityModifier && data.EnheritanceLocalMap.ContainsKey(local)) { continue; } if (local.GetStatic() == null) { //non Static types doesn't work in this context continue; } List<Node> nodeList = new List<Node>(); nodeList.Add(structDecl); nodeList.Add(local); targets[i].Add(nodeList); } foreach (APropertyDecl local in data.StructProperties[structDecl]) { if (local.GetName().Text != name) continue; //Must be public if we are outside the struct //If it's an enherited private variable, you can't refer to it. if (currentStruct != structDecl && !(local.GetVisibilityModifier() is APublicVisibilityModifier)) { continue; } if (local.GetStatic() == null) { //non Static types doesn't work in this context continue; } List<Node> nodeList = new List<Node>(); nodeList.Add(structDecl); nodeList.Add(local); targets[i].Add(nodeList); } } else { if (type is ANamedType && data.StructTypeLinks.ContainsKey((ANamedType)type) && !(data.Enums.ContainsKey(data.StructTypeLinks[(ANamedType)type]))) { AStructDecl targetStruct = data.StructTypeLinks[(ANamedType)type]; foreach (AALocalDecl local in data.StructFields[targetStruct]) { if (local.GetName().Text != name) continue; //Must be public if we are outside the struct //If it's an enherited private variable, you can't refer to it. if (currentStruct != targetStruct && !(local.GetVisibilityModifier() is APublicVisibilityModifier) || currentStruct == targetStruct && local.GetVisibilityModifier() is APrivateVisibilityModifier && data.EnheritanceLocalMap.ContainsKey(local)) { continue; } if (local.GetStatic() != null) { //Static types doesn't work in this context continue; } List<Node> nodeList = new List<Node>(); nodeList.AddRange(list); nodeList.Add(local); targets[i].Add(nodeList); } foreach (APropertyDecl local in data.StructProperties[targetStruct]) { if (local.GetName().Text != name) continue; //Must be public if we are outside the struct //If it's an enherited private variable, you can't refer to it. if (currentStruct != targetStruct && !(local.GetVisibilityModifier() is APublicVisibilityModifier)) { continue; } if (local.GetStatic() != null) { //Static types doesn't work in this context continue; } List<Node> nodeList = new List<Node>(); nodeList.AddRange(list); nodeList.Add(local); targets[i].Add(nodeList); } } else//Find matching enrichment { List<IList> visibleDecls = Util.GetVisibleDecls(node, true); AEnrichmentDecl currentEnrichment = Util.GetAncestor<AEnrichmentDecl>(node); foreach (IList declList in visibleDecls) { foreach (PDecl decl in declList) { if (decl is AEnrichmentDecl) { AEnrichmentDecl aDecl = (AEnrichmentDecl)decl; if (Util.TypesEqual(aDecl.GetType(), type, data)) { foreach (PDecl enrichmentDecl in aDecl.GetDecl()) { if (enrichmentDecl is APropertyDecl) { APropertyDecl local = (APropertyDecl)enrichmentDecl; if (local.GetName().Text != name) continue; //Must be public if we are outside the struct if (currentEnrichment != aDecl && !(local.GetVisibilityModifier() is APublicVisibilityModifier)) { continue; } if (local.GetStatic() != null) { //Static types doesn't work in this context continue; } List<Node> nodeList = new List<Node>(); nodeList.AddRange(list); nodeList.Add(local); targets[i].Add(nodeList); } } } } } } //Could be array.length if ((type is AArrayTempType || type is ADynamicArrayType) && name == "length") { List<Node> nodeList = new List<Node>(); nodeList.AddRange(list); nodeList.Add((TIdentifier)node.GetIdentifier()[names.Count - 1]); targets[i].Add(nodeList); } } } } } AASourceFile currentFile = Util.GetAncestor<AASourceFile>(node); List<string> currentNamespace = Util.GetFullNamespace(node); foreach (ANamespaceDecl ns in baseNamespaces) { bool isSameFile = currentFile == Util.GetAncestor<AASourceFile>(ns); foreach (PDecl decl in ns.GetDecl()) { if (decl is AFieldDecl) { AFieldDecl aDecl = (AFieldDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !isSameFile && aDecl.GetStatic() != null) continue; targets[2].Add(new List<Node>(){decl}); } else if (decl is APropertyDecl) { APropertyDecl aDecl = (APropertyDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !isSameFile && aDecl.GetStatic() != null) continue; targets[2].Add(new List<Node>() { decl }); } else if (decl is AStructDecl) { AStructDecl aDecl = (AStructDecl)decl; if (aDecl.GetName().Text != name) continue; bool isSameNamespace = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (!isSameNamespace && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier) continue; targets[2].Add(new List<Node>() { decl }); } else if (decl is ANamespaceDecl) { ANamespaceDecl aDecl = (ANamespaceDecl)decl; if (aDecl.GetName().Text != name) continue; namespaces.Add(aDecl); } } } } //If we got no matches, and we are not last, report error if (errors != null && node.GetIdentifier().Count > names.Count && targets[0].Count + targets[1].Count + targets[2].Count + namespaces.Count == 0) { string dotList = ""; foreach (string s in names) { if (dotList != "") dotList += "."; dotList += s; } errors.Add(new ErrorCollection.Error((TIdentifier)node.GetIdentifier()[names.Count - 1], dotList + LocRM.GetString("ErrorText174"))); reportedError = true; } }
public EnviromentChecking(ErrorCollection errors, SharedData data, bool doChecks = true) { this.errors = errors; this.data = data; this.doChecks = doChecks; //Check that no name is used twice //Can distinguish between structs, fields and methods in the context. So check other things of same type in user data and includes #region Check dublicates if (doChecks) { //Methods for (int i = 0; i < data.Methods.Count; i++) { AMethodDecl method = data.Methods[i].Decl; string signature = Util.GetMethodSignature(method); //User data /*for (int j = i + 1; j < data.Methods.Count; j++) { if (signature == Util.GetMethodSignature(data.Methods[j].Decl) && (Util.IsVisible(data.Methods[i].Decl, data.Methods[j].Decl) || Util.IsVisible(data.Methods[j].Decl, data.Methods[i].Decl))) { errors.Add(new ErrorCollection.Error(method.GetName(), data.Methods[i].File, "Dublicate methods", false)); errors.Add(new ErrorCollection.Error(data.Methods[j].Decl.GetName(), data.Methods[j].File, "Dublicate methods", false)); data.Methods[j].Decl.Parent().RemoveChild(data.Methods[j].Decl); data.Methods.RemoveAt(j); j--; } }*/ //Includes foreach (AMethodDecl methodDecl in data.Libraries.Methods) { if (signature == Util.GetMethodSignature(methodDecl) && (methodDecl.GetBlock() != null || methodDecl.GetNative() != null)) { errors.Add(new ErrorCollection.Error(method.GetName(), data.Methods[i].File, "Method has same signature as a library method.", false)); data.Methods[i].Decl.Parent().RemoveChild(data.Methods[i].Decl); data.Methods.RemoveAt(i); i--; break; } } //Triggers /*if (method.GetFormals().Count == 2 && ((AALocalDecl)method.GetFormals()[0]).GetType() is ANamedType && ((ANamedType)((AALocalDecl)method.GetFormals()[0]).GetType()).GetName().Text == "bool" && ((AALocalDecl)method.GetFormals()[1]).GetType() is ANamedType && ((ANamedType)((AALocalDecl)method.GetFormals()[1]).GetType()).GetName().Text == "bool") foreach (ATriggerDecl trigger in data.Triggers) { if (trigger.GetName().Text == method.GetName().Text) { errors.Add(new ErrorCollection.Error(method.GetName(), data.Methods[i].File, "Method has same signature as a library method. You can uncheck the library from the include list.", false)); data.Methods[i].Decl.Parent().RemoveChild(data.Methods[i].Decl); data.Methods.RemoveAt(i); i--; break; } }*/ } //Fields for (int i = 0; i < data.Fields.Count; i++) { AFieldDecl field = data.Fields[i].Decl; //User data /*for (int j = i + 1; j < data.Fields.Count; j++) { if (field.GetName().Text == data.Fields[j].Decl.GetName().Text && (Util.IsVisible(data.Fields[i].Decl, data.Fields[j].Decl) || Util.IsVisible(data.Fields[j].Decl, data.Fields[i].Decl))) { errors.Add(new ErrorCollection.Error(field.GetName(), data.Fields[i].File, "Dublicate fields", false)); errors.Add(new ErrorCollection.Error(data.Fields[j].Decl.GetName(), data.Fields[j].File, "Dublicate fields", false)); data.Fields[j].Decl.Parent().RemoveChild(data.Fields[j].Decl); data.Fields.RemoveAt(j); j--; } }*/ //Includes foreach (AFieldDecl fieldDecl in data.Libraries.Fields) { if (field.GetName().Text == fieldDecl.GetName().Text) { errors.Add(new ErrorCollection.Error(field.GetName(), data.Structs[i].File, "Field has the same name as an included field.", false)); field.Parent().RemoveChild(field); data.Structs.RemoveAt(i); i--; break; } } } //Enrichments foreach (AEnrichmentDecl enrichment in data.Enrichments) { //Constructors { List<AConstructorDecl> list = new List<AConstructorDecl>(); list.AddRange(enrichment.GetDecl().OfType<AConstructorDecl>()); for (int i = 0; i < list.Count; i++) { string sig1 = Util.GetConstructorSignature(list[i]); for (int j = i + 1; j < list.Count; j++) { string sig2 = Util.GetConstructorSignature(list[j]); if (sig1 == sig2) { errors.Add(new ErrorCollection.Error(enrichment.GetToken(), currentFile, "Two constructors found with the signature " + sig1)); } } } } //Deconstructors { List<ADeconstructorDecl> list = new List<ADeconstructorDecl>(); list.AddRange(enrichment.GetDecl().OfType<ADeconstructorDecl>()); if (list.Count > 1) { List<ErrorCollection.Error> subErrors = new List<ErrorCollection.Error>(); foreach (ADeconstructorDecl deconstructor in list) { subErrors.Add(new ErrorCollection.Error(deconstructor.GetName(), "Deconstructor")); } errors.Add(new ErrorCollection.Error(enrichment.GetToken(), "Multiple deconstructors found in enrichment. Only one is allowed.")); } } } //Structs for (int i = 0; i < data.Structs.Count; i++) { AStructDecl str = data.Structs[i].Decl; //User data /*for (int j = i + 1; j < data.Structs.Count; j++) { if (str.GetName().Text == data.Structs[j].Decl.GetName().Text && (Util.IsVisible(data.Structs[i].Decl, data.Structs[j].Decl) || Util.IsVisible(data.Structs[j].Decl, data.Structs[i].Decl))) { errors.Add(new ErrorCollection.Error(str.GetName(), data.Structs[i].File, "Dublicate structs", false)); errors.Add(new ErrorCollection.Error(data.Structs[j].Decl.GetName(), data.Structs[j].File, "Dublicate structs", false)); data.Structs[j].Decl.Parent().RemoveChild(data.Structs[j].Decl); data.Structs.RemoveAt(j); j--; } }*/ //Includes foreach (AStructDecl structDecl in data.Libraries.Structs) { if (str.GetName().Text == structDecl.GetName().Text) { errors.Add(new ErrorCollection.Error(str.GetName(), data.Structs[i].File, "Struct has the same name as an included struct.", false)); str.Parent().RemoveChild(str); data.Structs.RemoveAt(i); i--; break; } } //Constructors for (int j = 0; j < data.StructConstructors[str].Count; j++) { string sig1 = Util.GetConstructorSignature(data.StructConstructors[str][j]); for (int k = j + 1; k < data.StructConstructors[str].Count; k++) { string sig2 = Util.GetConstructorSignature(data.StructConstructors[str][k]); if (sig1 == sig2) { errors.Add(new ErrorCollection.Error(str.GetName(), currentFile, "Two constructors found with the signature " + sig1)); } } } //Struct fields //if (data.StructFields[str].Count == 0) // errors.Add(new ErrorCollection.Error(str.GetName(), Util.GetAncestor<AASourceFile>(str), "A struct must have atleast one field", false)); for (int j = 0; j < data.StructFields[str].Count; j++) { AALocalDecl field = data.StructFields[str][j]; for (int k = j + 1; k < data.StructFields[str].Count; k++) { if (field.GetName().Text == data.StructFields[str][k].GetName().Text) { errors.Add(new ErrorCollection.Error(field.GetName(), data.Structs[i].File, "Dublicate struct fields", false)); errors.Add(new ErrorCollection.Error(data.StructFields[str][k].GetName(), data.Structs[i].File, "Dublicate struct fields", false)); data.StructFields[str][k].Parent().RemoveChild(data.StructFields[str][k]); data.StructFields[str].RemoveAt(k); j--; } } for (int k = 0; k < data.StructProperties[str].Count; k++) { if (field.GetName().Text == data.StructProperties[str][k].GetName().Text) { errors.Add(new ErrorCollection.Error(field.GetName(), data.Structs[i].File, "Dublicate struct fields", false)); errors.Add(new ErrorCollection.Error(data.StructProperties[str][k].GetName(), data.Structs[i].File, "Dublicate struct fields", false)); data.StructProperties[str][k].Parent().RemoveChild(data.StructFields[str][k]); data.StructProperties[str].RemoveAt(k); j--; } } } //Struct methods for (int j = 0; j < data.StructMethods[str].Count; j++) { AMethodDecl field = data.StructMethods[str][j]; for (int k = j + 1; k < data.StructMethods[str].Count; k++) { if (Util.GetMethodSignature(field) == Util.GetMethodSignature(data.StructMethods[str][k])) { errors.Add(new ErrorCollection.Error(field.GetName(), data.Structs[i].File, "Dublicate struct methods", false)); errors.Add(new ErrorCollection.Error(data.StructMethods[str][j].GetName(), data.Structs[i].File, "Dublicate struct methods", false)); data.StructMethods[str][k].Parent().RemoveChild(data.StructMethods[str][k]); data.StructMethods[str].RemoveAt(k); j--; } } } } //type defs foreach (ATypedefDecl typedef in data.Typedefs) { ANamedType namedType = (ANamedType) typedef.GetName(); AAName name = (AAName) namedType.GetName(); if (name.GetIdentifier().Count > 1) { errors.Add(new ErrorCollection.Error(typedef.GetToken(), "You can only typedef to a simple name. Use namespaces if you want to refference it with dots.")); } else { if (GalaxyKeywords.Primitives.words.Contains(((TIdentifier)name.GetIdentifier()[0]).Text)) { errors.Add(new ErrorCollection.Error(typedef.GetToken(), Util.GetAncestor<AASourceFile>(typedef), "You can not overwrite primitive names with typedefs.")); } } } } #endregion }
/// <summary> /// Creates a BaseBuilder-derived object from a name /// </summary> /// <param name="parentBuilder">Parent builder</param> /// <param name="parameters">Load parameters</param> /// <param name="errors">Error collection</param> /// <param name="reader">XML reader</param> /// <returns>Returns the new builder, or null if there as an error</returns> public static BaseBuilder CreateBuilderFromReader( BaseBuilder parentBuilder, ComponentLoadParameters parameters, ErrorCollection errors, XmlReader reader ) { BaseBuilder result = null; try { switch ( reader.Name ) { case "null" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, null ); break; case "rb" : result = new RootBuilder( parameters, errors, reader ); break; case "object" : result = new ObjectBuilder( parameters, errors, reader, parentBuilder ); break; case "ref" : result = new ReferenceBuilder( parameters, errors, reader, parentBuilder ); break; case "asset" : result = new AssetBuilder( parameters, errors, reader, parentBuilder ); break; case "instance" : result = new InstanceBuilder( parameters, errors, reader, parentBuilder ); break; case "method" : result = new MethodBuilder( parameters, errors, reader, parentBuilder ); break; case "list" : result = new ListBuilder( parameters, errors, reader, parentBuilder ); break; case "table" : result = new DictionaryBuilder( parameters, errors, reader, parentBuilder ); break; case "type" : result = new TypeBuilder( parameters, errors, reader, parentBuilder ); break; case "template" : result = new TemplateBuilder( parameters, errors, reader, parentBuilder ); break; case "location" : string loc = reader.GetAttribute( "value" ); result = new ValueBuilder( parameters, errors,reader, parentBuilder, Locations.NewLocation( loc ) ); break; case "dictionaryEntry" : result = new DictionaryEntryBuilder( parameters, errors, reader, parentBuilder ); break; case "dynProperty" : object dynPropertyValue = parameters.Properties[ reader.GetAttribute( "value" ) ]; result = new ValueBuilder( parameters, errors, reader, parentBuilder, dynPropertyValue ); break; case "colour" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, MakeColour( reader ) ); break; case "string" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, reader.GetAttribute( "value" ) ); break; case "guid" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, new Guid( reader.GetAttribute( "value" ) ) ); break; case "bool" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, bool.Parse( reader.GetAttribute( "value" ) ) ); break; case "char" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, char.Parse( reader.GetAttribute( "value" ) ) ); break; case "byte" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, byte.Parse( reader.GetAttribute( "value" ) ) ); break; case "sbyte" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, sbyte.Parse( reader.GetAttribute( "value" ) ) ); break; case "short" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, short.Parse( reader.GetAttribute( "value" ) ) ); break; case "ushort" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, ushort.Parse( reader.GetAttribute( "value" ) ) ); break; case "int" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, int.Parse( reader.GetAttribute( "value" ) ) ); break; case "uint" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, uint.Parse( reader.GetAttribute( "value" ) ) ); break; case "long" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, long.Parse( reader.GetAttribute( "value" ) ) ); break; case "ulong" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, ulong.Parse( reader.GetAttribute( "value" ) ) ); break; case "float" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, float.Parse( reader.GetAttribute( "value" ) ) ); break; case "double" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, double.Parse( reader.GetAttribute( "value" ) ) ); break; case "timeSpan" : result = new ValueBuilder( parameters, errors, reader, parentBuilder, MakeTimeSpan( reader ) ); break; case "point3" : { float x = float.Parse( reader.GetAttribute( "x" ) ); float y = float.Parse( reader.GetAttribute( "y" ) ); float z = float.Parse( reader.GetAttribute( "z" ) ); result = new ValueBuilder( parameters, errors, reader, parentBuilder, new Point3( x, y, z ) ); break; } case "bigPoint3" : { long x = long.Parse( reader.GetAttribute( "x" ) ); long y = long.Parse( reader.GetAttribute( "y" ) ); long z = long.Parse( reader.GetAttribute( "z" ) ); result = new ValueBuilder( parameters, errors, reader, parentBuilder, new BigPoint3( x, y, z ) ); break; } case "vector2" : { float x = float.Parse( reader.GetAttribute( "x" ) ); float y = float.Parse( reader.GetAttribute( "y" ) ); result = new ValueBuilder( parameters, errors, reader, parentBuilder, new Vector2( x, y ) ); break; } case "vector3" : { float x = float.Parse( reader.GetAttribute( "x" ) ); float y = float.Parse( reader.GetAttribute( "y" ) ); float z = float.Parse( reader.GetAttribute( "z" ) ); result = new ValueBuilder( parameters, errors, reader, parentBuilder, new Vector3( x, y, z ) ); break; } case "point2" : case "quat" : { errors.Add( reader, "Element is not yet supported", reader.Name ); reader.Skip( ); break; } default : { // Interpret name as object type string typeName = reader.Name; result = new ObjectBuilder( parameters, errors, reader, parentBuilder, typeName ); break; } } } catch ( Exception ex ) { errors.Add( reader, ex, "Builder created from element \"{0}\" threw an exception", reader.Name ); reader.Skip( ); } if ( result != null ) { string name = reader.Name; try { result.ReadChildBuilders( reader ); } catch ( Exception ex ) { errors.Add( reader, ex, "Exception thrown while reading children from builder \"{0}\"", name ); } } return result; }
/// <summary> /// Валидация страницы /// </summary> /// <param name="columnName">Название элемента для валидации</param> /// <returns></returns> public override string Validate(string columnName) { // Текст ошибки string error = null; switch (columnName) { case nameof(Login): Login = Login.Trim(); if (string.IsNullOrEmpty(Login)) { error = "Логин не введён"; } else if (Login.Length < 3) { error = "Минимум 3 символа"; } else if (Login.Length > 150) { error = "Максимум 150 символов"; } else if (RaP_DAO.IsLoginExists(id ?? 0, Login)) { error = "Этот логин занят"; } else { // Проверка, что в логин состоит только из букв и цифр bool onlyLettersAndDigits = false; bool atLeastOneLetter = false; for (int i = 0; i < Login.Length && !onlyLettersAndDigits && !atLeastOneLetter; i++) { onlyLettersAndDigits = char.IsLetter(Login[i]) || char.IsDigit(Login[i]); atLeastOneLetter = char.IsLetter(Password[i]); } if (!onlyLettersAndDigits) { error = "Логин должен состоять только из букв и цифр"; } else if (!atLeastOneLetter) { error = "Введите хотя бы 1 букву"; } } break; case nameof(Password): Password = Password.Trim(); if (string.IsNullOrEmpty(Password)) { error = "Введите пароль"; } else if (Password.Length < 6) { error = "Минимум 6 символов"; } else if (Password.Length > 50) { error = "Максимум 50 символов"; } else if (Password == Login) { error = "Пароль не может совпадать с логином"; } else { // Проверка, что в пароле есть хотя бы 1 буква bool atLeastOneLetter = false; for (int i = 0; i < Password.Length && !atLeastOneLetter; i++) { atLeastOneLetter = char.IsLetter(Password[i]); } if (!atLeastOneLetter) { error = "Введите хотя бы 1 букву"; } } break; case nameof(SelectedCompany): if (SelectedCompany == null) { error = "Выберите компанию сотрудника"; } break; } if (ErrorCollection.ContainsKey(columnName)) { ErrorCollection[columnName] = error; } else { ErrorCollection.Add(columnName, error); } OnPropertyChanged(nameof(ErrorCollection)); return(error); }
/// <summary> /// Adds the specified obj. /// </summary> /// <param name="obj">The obj.</param> /// <returns></returns> public SPSConfigError Add(SPSConfigError obj) { return(ErrorCollection.Add(obj)); }
public ErrorCollection CreateX264File() { _errors = _validationService.Validate(); if (_errors.Count() == 0) { switch (_x264FileSettings.EncodeType) { case EnumEncodeType.CRF: this.CreateCRFX264File(); break; case EnumEncodeType.TwoPass: this.CreateTwoPassX264File(); break; default: _errors.Add(new Error() { Description = "Invalid x264 encode type" }); break; } } return _errors; }
/// <summary> /// Validates the project file after it has been loaded from an INI file. /// </summary> public void ValidateProject() { // Validate stub ValidateStubIcon(); ValidateStubPadding(); ValidateManifest(); // Validate sources ValidateSources(); ValidateCompression(); ValidateEofData(); // Validate actions ValidateActions(); ValidateRunPE(); ValidateInvoke(); ValidateDrop(); ValidateMessageBox(); void ValidateStubIcon() { // Validate stub icon if (Project.Stub.IconPath != null) { // Validate that stub icon has .ico or .exe extension string extension = Path.GetExtension(Project.Stub.IconPath); if (extension.Equals(".ico", StringComparison.OrdinalIgnoreCase)) { // Validate that stub icon is a valid .ico file if (!IconExtractor.HasIcon(Project.Stub.IconPath)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "File '" + Path.GetFileName(Project.Stub.IconPath) + "' is not a valid icon."); } } else if (extension.Equals(".exe", StringComparison.OrdinalIgnoreCase)) { // Validate that stub icon is an executable file with an icon if (!IconExtractor.HasIcon(Project.Stub.IconPath)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Could not extract icon from '" + Path.GetFileName(Project.Stub.IconPath) + "'."); } } else { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Stub icon must have '.ico' or '.exe' extension."); } } } void ValidateStubPadding() { // Validate that stub has padding if (Project.Stub.Padding < 50) { Errors.Add(ErrorSource.Project, ErrorSeverity.Warning, "Padding is less than 50. The compiled binary will be of high-entropy and may be detected as a packer."); } } void ValidateManifest() { // Validate that manifest is not set to both template and cutom file if (Project.Manifest.Template != null && Project.Manifest.Path != null) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Both manifest template and path specified. Please specify only one."); } } void ValidateSources() { // Validate duplicate source ID's for (int i = 0; i < Project.Sources.Count; i++) { if (Project.Sources.Skip(i + 1).Any(source => source.Id == Project.Sources[i].Id)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Duplicate source ID '" + Project.Sources[i].Id + "'."); } } // Exclude unused sources foreach (ProjectSource source in Project.Sources.ToArray()) { if (Project.Actions.None(action => action.Source == source)) { Project.RemoveSource(source); Errors.Add(ErrorSource.Project, ErrorSeverity.Warning, "Source '" + source.Id + "' was excluded, because it is not used."); } } } void ValidateCompression() { // Validate that compressed files are smaller than 100 MB foreach (EmbeddedSource source in Project.Sources.OfType <EmbeddedSource>()) { if (source.Compress && source.Path != null && new FileInfo(source.Path).Length > 1024 * 1024 * 100) { Errors.Add(ErrorSource.Project, ErrorSeverity.Warning, "File '" + Path.GetFileName(source.Path) + "' is bigger than 100 MB. It is recommended to disable compression."); } } } void ValidateEofData() { IEnumerable <EmbeddedSource> eofSources = Project.Sources.OfType <EmbeddedSource>().Where(source => source.EofData); // Validate that only PE files are used as EOF data sources foreach (EmbeddedSource source in eofSources) { if (new[] { ".exe", ".dll" }.None(extension => Path.GetExtension(source.Path).Equals(extension, StringComparison.OrdinalIgnoreCase))) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Cannot write EOF data of file '" + Path.GetFileName(source.Path) + "'. Only executable files contain EOF data."); } } // Validate that only one file's EOF data is written foreach (EmbeddedSource source in eofSources.Skip(1)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Cannot write EOF data of file '" + Path.GetFileName(source.Path) + "'. Only one file's EOF data can be written."); } } void ValidateActions() { // Validate that at least one action exists if (Project.Actions.None()) { Errors.Add(ErrorSource.Project, ErrorSeverity.Warning, "The project is empty."); } } void ValidateRunPE() { // Validate that RunPE files have an .exe extension foreach (RunPEAction action in Project.Actions.OfType <RunPEAction>()) { if (action.Source is EmbeddedSource embeddedSource && embeddedSource.Path != null && !Path.GetExtension(embeddedSource.Path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "RunPE file must have '.exe' extension."); } } } void ValidateInvoke() { // Validate that invoke files have an .exe extension foreach (InvokeAction action in Project.Actions.OfType <InvokeAction>()) { if (action.Source is EmbeddedSource embeddedSource && embeddedSource.Path != null && !Path.GetExtension(embeddedSource.Path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, "Invoked file must have '.exe' extension."); } } // Validate that invoke actions are only used in a .NET stub if (CSharp.EqualsNone(Project.Stub.Type, StubType.DotNet32, StubType.DotNet64) && Project.Actions.OfType <InvokeAction>().Any()) { Errors.Add(ErrorSource.Project, ErrorSeverity.Error, ".NET invocation is only supported in a .NET stub."); } } void ValidateDrop() { // Validate that a UAC manifest is included, if files are dropped in privileged directories IEnumerable <string> privilegedDropFileNames = Project.Actions .OfType <DropAction>() .Where(action => CSharp.EqualsAny(action.Location, DropLocation.WindowsDirectory, DropLocation.SystemDirectory, DropLocation.ProgramFiles, DropLocation.CDrive)) .Select(action => { if (action.FileName != null) { return(action.FileName); } else if (action.Source is EmbeddedSource embeddedSource && embeddedSource.Path != null) { return(Path.GetFileName(embeddedSource.Path)); }