Пример #1
0
        public void VisitDeclaration(DeclarationNode node)
        {
            _variables.Add(node, _currentOffset);
            IType type = ((TypeSpecifierNode)node.Type).Type;

            _currentOffset += _typeSizeManager.GetSize(type);
        }
Пример #2
0
        public FullScreenQuadVS()
        {
            Name             = "FullScreenQuadVS";
            Type             = ShaderType.Vertex;
            FeatureLevel     = FeatureLevel.VS_4_0_Level_9_1;
            KeyPart          = new TechniqueKey(vs: VertexShaderFlags.Position | VertexShaderFlags.TextureUV | VertexShaderFlags.Normal);
            EnableSeparators = true;
            InputStruct      = Struct.VertexPositionNormalTexture;
            OutputStruct     = SpriteVS.VSOut;

            Structs.ConstantBuffer cbStatic = SpriteVS.CBStatic;
            Add(cbStatic);

            DeclarationNode nClip = ClipSpaceTransformNode.FullScreenNode(InputStruct, cbStatic[Param.Vectors.ViewportSize]);

            CustomOutputNode outputNode = new CustomOutputNode()
            {
                Output = OutputStruct
            };

            outputNode.RegisterField(Vector.ClipPosition, nClip, Shaders.Type.Float4);
            outputNode.RegisterField(Vector.TextureUV, new ReferenceNode {
                Value = InputStruct[Param.SemanticVariables.Texture]
            }, Shaders.Type.Float2);

            Result = outputNode;
        }
Пример #3
0
        private static void EnsureDeclarationNode(DeclarationNode declarationNode, RulesetNode ruleSetNode, MediaNode mediaQueryNode, StyleSheetNode actualCss)
        {
            var rules = actualCss.StyleSheetRules.ToArray();
            var expectedMediaQuery = string.Empty;

            if (mediaQueryNode != null)
            {
                expectedMediaQuery = mediaQueryNode.PrintSelector();
                rules = rules.OfType <MediaNode>().Where(r => r.PrintSelector().Equals(expectedMediaQuery)).SelectMany(mq => mq.Rulesets).ToArray();
            }

            var expectedRule = ruleSetNode.PrintSelector();
            var declarations = rules
                               .OfType <RulesetNode>()
                               .Where(rsn => rsn.PrintSelector().Equals(expectedRule))
                               .SelectMany(r => r.Declarations).ToArray();

            var expectedproperty  = declarationNode.Property;
            var declarationValues = declarations.Where(d => d.Property.Equals(expectedproperty)).ToArray();

            var expectedValue = declarationNode.ExprNode.TermNode.MinifyPrint();

            if (!declarationValues.Any(d => d.ExprNode.TermNode.MinifyPrint().Equals(expectedValue)))
            {
                Assert.Fail("Could not find [{0}] --> [{1}] --> {2}: {3}; ".InvariantFormat(expectedMediaQuery, expectedRule, expectedproperty, expectedValue));
            }
        }
Пример #4
0
 public override void Visit(DeclarationNode node)
 {
     foreach (var i in node.IdentList)
     {
         i.Visit(this);
     }
 }
Пример #5
0
        public void VisitDeclaration(DeclarationNode node)
        {
            // Don't insert unreachable code
            if (!_builder.InsertBlock.IsValid)
            {
                return;
            }

            node.Assignment.AcceptExpressionVisitor(this);
            if (!_visitedValue.IsValid)
            {
                return;
            }

            Metadata dbgLocation = SetCurrentDebugLocation(node);

            _function.VariableValues.TryGetValue(node, out Value varStorage);

            if (_genContext.DebugInfo)
            {
                _genContext.TryGetNodeSymbol(node, out Symbol varRange);
                Metadata varType     = _genContext.LookupDiType(node.Type) !.Value;
                Metadata varMetadata = _genContext.DiBuilder.CreateAutoVariable(_lexicalScope, node.Name,
                                                                                _genContext.DiFile, varRange.LLVMLine, varType, true, LLVMDIFlags.LLVMDIFlagZero,
                                                                                varType.GetTypeAlignInBits());
                _genContext.DiBuilder.InsertDeclareAtEnd(varStorage, varMetadata,
                                                         _genContext.DiBuilder.CreateExpression(), dbgLocation, _builder.InsertBlock);
            }

            _visitedValue = _builder.BuildStore(_visitedValue, varStorage);
        }
Пример #6
0
 public ForNode(DeclarationNode declaration, IExpressionNode condition, IExpressionNode update, BodyNode body)
 {
     Declaration = declaration;
     Condition   = condition;
     Update      = update;
     Body        = body;
 }
Пример #7
0
        public void VisitFunctionCall(FunctionCallNode node)
        {
            node.LHS.ReturnType.AcceptSyntaxTreeVisitor(_delegator);

            for (int i = 0, ilen = node.Arguments.Count; i < ilen; ++i)
            {
                DeclarationNode parameter = node.LHS.Parameters[i];
                IExpressionNode argument  = node.Arguments[i];

                // TypeSpecifiers should be resolved at this point.
                TypeSpecifierNode typeSpecifier = (TypeSpecifierNode)parameter.Type;
                IType             parameterType = typeSpecifier.Type;
                IType             argumentType  = GetExpressionType(argument);

                if (parameterType != argumentType)
                {
                    string message = $"Type mismatch between parameter and positional argument {i}.\n" +
                                     $"  Parameter: {parameterType.Represent()}\n" +
                                     $"  Argument: {argumentType.Represent()}";
                    _errors.AddError(message, node);
                }
            }

            SetAndCacheType(node, Type);
        }
Пример #8
0
        private string CreateParameters(DeclarationNode procedureDeclaration, ScopedSymbolTable symbols)
        {
            string param = "";

            for (var index = 0; index < procedureDeclaration.Parameters.Count; index++)
            {
                var p       = procedureDeclaration.Parameters[index];
                var name    = p.Declaration.VarNode.VariableName;
                var matches = symbols.LookupSymbols <Symbol>(name, true);

                if (matches.Count > 1)
                {
                    name = current.AddAlias(name);
                }

                param +=
                    $"{typesConverter.GetTypeName(p.Declaration.TypeNode.TypeValue)} {name}";
                if (index != procedureDeclaration.Parameters.Count - 1)
                {
                    param += ",";
                }
            }

            return(param);
        }
Пример #9
0
        private void ParseMethodParameters(List <Token> tokens, ref int index, MethodNode method)
        {
            int count = 0;

            do
            {
                if (index >= tokens.Count)
                {
                    throw new ParserException(tokens.Last(), ParserException.Kind.EndOfStream);
                }

                if (count > 0)
                {
                    ExpectDelimiter(tokens, ref index, ",");
                }

                var arg = new ParameterNode(method);

                var decl     = new DeclarationNode(arg);
                var typeText = ExpectIdentifier(tokens, ref index, true);

                decl.type = GetTypeFromToken(method, typeText);
                if (decl.type == null)
                {
                    throw new ParserException(tokens.Last(), ParserException.Kind.ExpectedType);
                }

                decl.identifier = ExpectIdentifier(tokens, ref index, false);

                count++;
            } while (tokens[index].text != ")");
        }
Пример #10
0
        /// <summary>Initializes a new instance of the Background class
        /// Example:
        /// #selector
        /// {
        ///   background: url(../../i/02/3118D8F3781159C8341246BBF2B4CA.gif) no-repeat -10px -200px;
        /// }</summary>
        /// <param name="declarationAstNode">The background declaration node</param>
        /// <param name="outputUnit">The output unit.</param>
        /// <param name="outputUnitFactor">The output unit factor.</param>
        internal Background(DeclarationNode declarationAstNode, string outputUnit, double outputUnitFactor)
        {
            Contract.Requires(declarationAstNode != null);

            this.DeclarationAstNode = declarationAstNode;
            this.BackgroundImage    = new BackgroundImage();
            this.BackgroundPosition = new BackgroundPosition(outputUnit, outputUnitFactor);
            this.BackgroundRepeat   = new BackgroundRepeat();

            var expr     = declarationAstNode.ExprNode;
            var termNode = expr.TermNode;

            // Parse term
            this.BackgroundImage.ParseTerm(termNode);
            this.BackgroundPosition.ParseTerm(termNode);
            this.BackgroundRepeat.ParseTerm(termNode);

            // Parse term with operator
            expr.TermsWithOperators.ForEach(termWithOperator =>
            {
                this.BackgroundImage.ParseTermWithOperator(termWithOperator);
                this.BackgroundPosition.ParseTermWithOperator(termWithOperator);
                this.BackgroundRepeat.ParseTermWithOperator(termWithOperator);
            });
        }
Пример #11
0
 public void Visit(DeclarationNode node)
 {
     Console.ForegroundColor = ConsoleColor.DarkBlue;
     Console.Write(Indent + "DeclarationNode: " + node.Type + " " + node.Identifier + " ");
     node.RightHandSide.Accept(this);
     Console.Write("\n");
     Console.ResetColor();
 }
Пример #12
0
        /// <summary>Updates declaration based on property keys/values. If property has a key or a value that contains
        /// "Excluded", then such a property will be excluded from the updated declaration.</summary>
        /// <example>The "background-image" will be excluded from the following CSS selector:
        /// #selector
        /// {
        ///   background-position: -10px  -200px;
        ///   background-image: Excluded;
        ///   background-image: url(../../i/02/3118D8F3781159C8341246BBF2B4CA.gif);
        /// }</example>
        /// <example>The "Excluded-right" will be excluded from the following CSS selector:
        /// #selector
        /// {
        ///   Excluded-right: -10px;
        ///   background-image: url(../../i/02/3118D8F3781159C8341246BBF2B4CA.gif);
        /// }</example>
        /// <param name="declarationNode">The declaration node</param>
        /// <returns>The updated declaration node</returns>
        public override AstNode VisitDeclarationNode(DeclarationNode declarationNode)
        {
            if (declarationNode == null)
            {
                throw new ArgumentNullException("declarationNode");
            }

            return(declarationNode.MinifyPrint().Contains(ExcludedSubstring) ? null : declarationNode);
        }
Пример #13
0
 internal Parameter(DeclarationNode node)
 {
     DecNode     = node;
     Name        = node.NameString;
     Display     = node.AsString;
     Description = null;
     UoTypeToken = node.UoTypeToken;
     Type        = UoTypeToken == null /*any*/ ? null : UoTypeToken.Value;
 }
Пример #14
0
            public override string Visit(DeclarationNode node, CssVisitorParams p)
            {
                var property = node.Property.Accept(this, p);
                var value    = node.Value.Accept(this, p);

                p.RuleBuilder.AddDeclaration(property, value);

                return(null);
            }
Пример #15
0
        public void VisitDeclaration(DeclarationNode node)
        {
            node.Assignment.AcceptExpressionVisitor(this);

            int resultSize = GetExpressionResultSize(node.Assignment);
            int addr       = _functionBuilder.AddInstruction(OpCode.WRITE, _layout.Variables[node], resultSize);

            _functionBuilder.AddInstruction(OpCode.POP, 0, resultSize);

            _functionBuilder.AddDebugSymbol(addr, node);
        }
        public void Visit_DeclarationWithNewName_LogsNoError()
        {
            // Arrange
            DeclarationNode declarationNode = new DeclarationNode(StandardTypes.Int, new IdentifierNode("myInt", DummySrcPos), DummySrcPos);

            // Act
            Checker.Visit(declarationNode);

            // Assert
            Assert.IsTrue(ErrorLogger.Errors.Count == 0);
        }
        public void Visit_DeclarationWithAlreadyDeclaredName_LogsVariableAlreadyDeclaredError()
        {
            // Arrange
            DeclarationNode declarationNode = new DeclarationNode(StandardTypes.Player, new IdentifierNode("player", DummySrcPos), DummySrcPos);

            // Act
            Checker.Visit(declarationNode);

            // Assert
            Assert.IsTrue(ErrorLogger.Errors.Count == 1 && ErrorLogger.Errors.First() is VariableAlreadyDeclaredError);
        }
Пример #18
0
        /// <summary>Initializes a new instance of the BackgroundRepeat class</summary>
        /// <param name="declarationNode">The declaration node</param>
        internal BackgroundRepeat(DeclarationNode declarationNode)
        {
            if (declarationNode == null)
            {
                throw new ArgumentNullException("declarationNode");
            }

            var expr = declarationNode.ExprNode;

            this.ParseTerm(expr.TermNode);
            expr.TermsWithOperators.ForEach(this.ParseTermWithOperator);
        }
Пример #19
0
        public void DeclarationNodeHasCorrectTypeAndId()
        {
            // https://stackoverflow.com/questions/39386586/c-sharp-generic-interface-and-factory-pattern
            AstNode astMads = astRoot.GetChildren(2);

            Assert.That(astMads, Is.TypeOf <DeclarationNode>());

            DeclarationNode dclMads = astMads as DeclarationNode;

            Assert.That(dclMads.Identifier, Is.EqualTo("mads"));
            Assert.That(dclMads.Type, Is.EqualTo(LanguageType.Int));
        }
Пример #20
0
        /// <summary>The <see cref="DeclarationNode"/> visit implementation</summary>
        /// <param name="declarationNode">The declaration AST node</param>
        /// <returns>The modified AST node if modified otherwise the original node</returns>
        public override AstNode VisitDeclarationNode(DeclarationNode declarationNode)
        {
            if (declarationNode == null)
            {
                throw new ArgumentNullException("declarationNode");
            }

            // Validate the property for lower case
            ValidateForLowerCase(declarationNode.Property);

            return(declarationNode);
        }
        /// <summary>The <see cref="Ast.DeclarationNode"/> visit implementation</summary>
        /// <param name="declarationNode">The declaration AST node</param>
        /// <returns>The modified AST node if modified otherwise the original node</returns>
        public override AstNode VisitDeclarationNode(DeclarationNode declarationNode)
        {
            if (HasTokens(declarationNode.Property))
            {
                return(new DeclarationNode(
                           ReplaceTokens(declarationNode.Property, this.resources),
                           declarationNode.ExprNode.Accept(this) as ExprNode,
                           declarationNode.Prio,
                           declarationNode.ImportantComments));
            }

            return(base.VisitDeclarationNode(declarationNode));
        }
Пример #22
0
        /// <summary>Creates a declaration node from list of term with operator nodes</summary>
        /// <param name="declarationNode">The original declaration node</param>
        /// <param name="termWithOperatorNodes">The list of term with operator nodes</param>
        /// <returns>The new declaration node</returns>
        internal static DeclarationNode CreateDeclarationNode(this DeclarationNode declarationNode, List <TermWithOperatorNode> termWithOperatorNodes)
        {
            if (declarationNode == null || termWithOperatorNodes == null || termWithOperatorNodes.Count <= 0)
            {
                return(declarationNode);
            }

            var primaryTerm = termWithOperatorNodes[0].TermNode;

            termWithOperatorNodes.RemoveAt(0);

            return(new DeclarationNode(declarationNode.Property, new ExprNode(primaryTerm, termWithOperatorNodes.AsReadOnly(), null), declarationNode.Prio, declarationNode.ImportantComments));
        }
Пример #23
0
        private Type EnsureStructRecursive(StructNode structNode, HashSet <StructNode> closedSet)
        {
            // Check if struct has already been created
            Type?llvmStructType = Context.LookupStructType(structNode.Name);

            if (llvmStructType != null)
            {
                return(llvmStructType.Value);
            }

            // Add this node to closed set to avoid cycles
            if (closedSet.Contains(structNode))
            {
                throw new InvalidOperationException($"Cyclic struct member detected: {structNode.Name}");
            }
            closedSet.Add(structNode);

            // Head recursion is necessary to resolve non-forward-declared struct types
            Type[] memberTypes = new Type[structNode.Members.Count];
            for (int i = 0, ilen = structNode.Members.Count; i < ilen; ++i)
            {
                DeclarationNode member = structNode.Members[i];
                IType           tp     = ((TypeSpecifierNode)member.Type).Type;
                Type?           llvmTp = LookupType(tp);
                if (llvmTp != null)
                {
                    memberTypes[i] = llvmTp.Value;
                }
                else if (tp is StructType structType)
                {
                    memberTypes[i] = EnsureStructRecursive(structType.Struct, closedSet);
                }
                else
                {
                    throw new InvalidOperationException("Unable to ensure type recursively");
                }
            }

            // Actually create the LLVM type here
            Type newStructType = Context.CreateStruct(structNode.Name, memberTypes);

            ulong           sizeInBits    = TargetDataLayout.SizeOfTypeInBits(newStructType);
            uint            alignInBits   = TargetDataLayout.PreferredAlignmentOfType(newStructType);
            List <Metadata> diMemberTypes =
                structNode.Members.ConvertAll(d => LookupDiType(((TypeSpecifierNode)d.Type).Type) !.Value);

            // TODO: resolve declaration file and line
            DiBuilder.CreateStruct(structNode.Name, DiFile, 0, sizeInBits, alignInBits, diMemberTypes.ToArray());

            return(newStructType);
        }
Пример #24
0
 public override void Visit(DeclarationNode node)
 {
     WriteIndent();
     ProgramBuilder.Append(node.Type.ToString().ToLower());
     AddSpace();
     for (int i = 0; i < node.IdentList.Count - 1; ++i)
     {
         node.IdentList[i].Visit(this);
         ProgramBuilder.Append(", ");
     }
     node.IdentList[node.IdentList.Count - 1].Visit(this);
     ProgramBuilder.Append(';');
     NewLine();
 }
Пример #25
0
        public void Visit_DeclarationNode_EmitsCorrectCode()
        {
            // Arrange
            DeclarationNode declarationNode = new DeclarationNode(new IntTypeNode(0, DummySrcPos),
                                                                  new IdentifierNode("myInt", DummySrcPos), DummySrcPos);

            string expectedResult = "int myInt = 0;\n";

            // Act
            string actualResult = CodeGenerator.Visit(declarationNode);

            // Assert
            Assert.AreEqual(expectedResult, actualResult, actualResult);
        }
Пример #26
0
        public LanguageType Visit(DeclarationNode node)
        {
            if (node.RightHandSide != null)
            {
                var exprType = node.RightHandSide.Accept(this);
                if (exprType != node.Type)
                {
                    throw new AlangExeption(node, $"declared type {node.Type.ToLower()} cannot be used with type {exprType.ToLower()}");
                }
            }


            return(node.Type);
        }
Пример #27
0
        public void InvalidConstVarCopyDeclarationTest()
        {
            string script =
                @"int i = 0;
                  float j = i;";
            Parser p = ParserTestHelper.GetParserInstanceForScript(script);

            p.Execute();

            //peek last
            DeclarationNode jDeclaration = p.Tree.TreeRoot.Childrens[1] as DeclarationNode;

            //int jValue = (int)jDeclaration.Variable.Value;
        }
Пример #28
0
        public bool Covers(LValue other)
        {
            for (int i = 0, ilen = Math.Min(_path.Length, other._path.Length); i < ilen; ++i)
            {
                DeclarationNode a = _path[i];
                DeclarationNode b = other._path[i];

                if (a != b)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #29
0
        private void Visit(DeclarationNode node)
        {
            var typeName   = node.TypeNode.Data.Type.ToString();
            var typeSymbol = CurrentScope.Lookup(typeName);

            var varName   = node.VariableNode.Data.Value.ToString();
            var varSymbol = new VariableSymbol(varName, typeSymbol);

            if (CurrentScope.Lookup(varName, true) != null)
            {
                throw new InvalidOperationException($"Variable {varName} has already been declared.");
            }

            CurrentScope.Insert(varSymbol);
        }
Пример #30
0
        public override void Visit(DeclarationNode node)
        {
            Console.Write("local " + node.Type.ToLower() + (node.IsArray ? "[] " : " "));

            node.Id.Accept(this);

            if (node.InitialValue != null)
            {
                Console.Write(" = ");
                node.InitialValue.Accept(this);
            }

            Console.Write(";");
            PrettyPrintNewLine();
        }
        /// <summary>
        /// Builds a list of declarations from the nodes aggregated by a parent.
        /// </summary>
        private void BuildDeclarationList(DeclarationNode parent, List<DeclarationNode> declarations)
        {            
            if (parent == null) throw new ArgumentNullException("parent");
            if (declarations == null) throw new ArgumentNullException("declarations");

            // get list of children.
            IList<IReference> references = parent.Node.References.Find(ReferenceTypeIds.HierarchicalReferences, false, true, m_nodes.TypeTree);

            foreach (IReference reference in references)
            {
                // do not follow sub-type references.
                if (m_nodes.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HasSubtype))
                {
                    continue;
                }

                // find child (ignore children that are not in the node table).
                ILocalNode child = GetLocalNode(reference.TargetId) as ILocalNode;

                if (child == null)
                {
                    continue;
                }

                // create the declartion node.
                DeclarationNode declaration = new DeclarationNode();

                declaration.Node = child;
                declaration.BrowsePath = Utils.Format("{0}.{1}", parent.BrowsePath, child.BrowseName);

                declarations.Add(declaration);

                // recursively include aggregated children.
                NodeId modellingRule = child.ModellingRule;

                if (modellingRule == Objects.ModellingRule_Mandatory || modellingRule == Objects.ModellingRule_Optional)
                {
                    BuildDeclarationList(declaration, declarations);
                }
            }
        }
        /// <summary>
        /// Builds the list of declaration nodes for a type definition. 
        /// </summary>
        private void BuildDeclarationList(ILocalNode typeDefinition, List<DeclarationNode> declarations)
        {
            if (typeDefinition == null) throw new ArgumentNullException("typeDefinition");
            if (declarations == null) throw new ArgumentNullException("declarations");

            // guard against loops (i.e. common grandparents).
            for (int ii = 0; ii < declarations.Count; ii++)
            {
                if (Object.ReferenceEquals(declarations[ii].Node, typeDefinition))
                {
                    return;
                }
            }

            // create the root declaration for the type.
            DeclarationNode declaration = new DeclarationNode();

            declaration.Node = typeDefinition;
            declaration.BrowsePath = String.Empty;

            declarations.Add(declaration);

            // follow references to supertypes first.
            foreach (IReference reference in typeDefinition.References.Find(ReferenceTypeIds.HasSubtype, true, false, null))
            {
                ILocalNode supertype = GetLocalNode(reference.TargetId) as ILocalNode;

                if (supertype == null)
                {
                    continue;
                }

                BuildDeclarationList(supertype, declarations);
            }

            // add children of type.
            BuildDeclarationList(declaration, declarations);            
        }
        public void ApplyModellingRules(
            ILocalNode instance, 
            ILocalNode typeDefinition, 
            ILocalNode templateDeclaration, 
            ushort     namespaceIndex)
        {
            if (instance == null) throw new ArgumentNullException("instance");
            if (typeDefinition == null) throw new ArgumentNullException("typeDefinition");

            // check existing type definition.
            UpdateTypeDefinition(instance, typeDefinition.NodeId);

            // create list of declarations for the type definition (recursively collects definitions from supertypes).
            List<DeclarationNode> declarations = new List<DeclarationNode>();
            BuildDeclarationList(typeDefinition, declarations);
            
            // add instance declaration if provided.
            if (templateDeclaration != null)
            {
                DeclarationNode declaration = new DeclarationNode();

                declaration.Node = templateDeclaration;
                declaration.BrowsePath = String.Empty;

                declarations.Add(declaration);

                BuildDeclarationList(templateDeclaration, declarations);
            }

            // build list of instances to create.
            List<ILocalNode> typeDefinitions = new List<ILocalNode>();
            SortedDictionary<string,ILocalNode> instanceDeclarations = new SortedDictionary<string,ILocalNode>();
            SortedDictionary<NodeId,ILocalNode> possibleTargets = new SortedDictionary<NodeId,ILocalNode>();
            
            // create instances from declarations.
            // subtypes appear in list last so traversing the list backwards find the overridden nodes first.
            for (int ii = declarations.Count-1; ii >= 0; ii--)
            {
                DeclarationNode declaration = declarations[ii];
                
                // update type definition list.
                if (String.IsNullOrEmpty(declaration.BrowsePath))
                {
                    typeDefinitions.Add(declaration.Node);
                    continue;
                }

                // skip declaration if instance already exists.
                // (i.e. the declaration was overridden).
                if (instanceDeclarations.ContainsKey(declaration.BrowsePath))
                {
                    continue;
                }
                
                // update instance declaration list.
                instanceDeclarations[declaration.BrowsePath] = declaration.Node;
                                        
                // save the node as a possible target of references.
                possibleTargets[declaration.Node.NodeId] = declaration.Node; 
            }
            
            // build list of instances that already exist.
            SortedDictionary<string,ILocalNode> existingInstances = new SortedDictionary<string,ILocalNode>();
            BuildInstanceList(instance, String.Empty, existingInstances);

            // maps the instance declaration onto an instance node.
            Dictionary<NodeId,ILocalNode> instancesToCreate = new Dictionary<NodeId,ILocalNode>(); 
            
            // apply modelling rules to instance declarations.
            foreach (KeyValuePair<string,ILocalNode> current in instanceDeclarations)
            {
                string browsePath = current.Key;
                ILocalNode instanceDeclaration = current.Value;

                // check if the same instance has multiple browse paths to it.
                ILocalNode newInstance = null;
                
                if (instancesToCreate.TryGetValue(instanceDeclaration.NodeId, out newInstance))
                {   
                    continue;
                }
 
                // check for an existing instance.
                if (existingInstances.TryGetValue(browsePath, out newInstance))
                {
                    continue;
                }

                // apply modelling rule to determine whether to create a new instance.
                NodeId modellingRule = instanceDeclaration.ModellingRule;
                
                // always create a new instance if one does not already exist.
                if (modellingRule == Objects.ModellingRule_Mandatory)
                {               
                    if (newInstance == null)
                    {
                        newInstance = instanceDeclaration.CreateCopy(CreateUniqueNodeId());
                        AddNode(newInstance);
                    }
                }

                // ignore optional instances unless one has been specified in the existing tree.
                else if (modellingRule == Objects.ModellingRule_Optional)
                {                            
                    if (newInstance == null)
                    {
                        continue;
                    }
                }

                // always use the declaration node.
                else if (modellingRule == Objects.ModellingRule_MandatoryShared)
                {                            
                    newInstance = instanceDeclaration;
                }

                // ignore any unknown modelling rules.
                else
                {
                    continue;
                }

                // save the mapping between the instance declaration and the new instance.
                instancesToCreate[instanceDeclaration.NodeId] = newInstance;
            }
            
            // add references from type definitions to top level.
            foreach (ILocalNode type in typeDefinitions)
            {
                foreach (IReference reference in type.References)
                {
                    // ignore external references from type.
                    if (reference.TargetId.IsAbsolute)
                    {
                        continue;
                    }
                    
                    // ignore subtype references.
                    if (m_nodes.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HasSubtype))
                    {
                        continue;                            
                    }

                    // ignore targets that are not in the instance tree.
                    ILocalNode target = null;

                    if (!instancesToCreate.TryGetValue((NodeId)reference.TargetId, out target))
                    {
                        continue;
                    }

                    // add forward and backward reference.
                    AddReference(instance, reference.ReferenceTypeId, reference.IsInverse, target, true);
                }                  
            }
           
            // add references between instance declarations.
            foreach (ILocalNode instanceDeclaration in instanceDeclarations.Values)
            {
                // find the source for the references.
                ILocalNode source = null;

                if (!instancesToCreate.TryGetValue(instanceDeclaration.NodeId, out source))
                {
                    continue;
                }
                
                // check if the source is a shared node.
                bool sharedNode = Object.ReferenceEquals(instanceDeclaration, source);

                foreach (IReference reference in instanceDeclaration.References)
                {
                    // add external reference.
                    if (reference.TargetId.IsAbsolute)
                    {
                        if (!sharedNode)
                        {
                            AddReference(source, reference.ReferenceTypeId, reference.IsInverse, reference.TargetId);
                        }

                        continue;
                    }

                    // check for modelling rule.
                    if (reference.ReferenceTypeId == ReferenceTypeIds.HasModellingRule)
                    {
                        if (!source.References.Exists(ReferenceTypeIds.HasModellingRule, false, reference.TargetId, false, null))
                        {
                            AddReference(source, reference.ReferenceTypeId, false, reference.TargetId);
                        }

                        continue;                            
                    }

                    // check for type definition.
                    if (reference.ReferenceTypeId == ReferenceTypeIds.HasTypeDefinition)
                    {
                        if (!sharedNode)
                        {                        
                            UpdateTypeDefinition(source, instanceDeclaration.TypeDefinitionId);
                        }

                        continue;                            
                    }

                    // add targets that are not in the instance tree.
                    ILocalNode target = null;

                    if (!instancesToCreate.TryGetValue((NodeId)reference.TargetId, out target))
                    {
                        // don't update shared nodes because the reference should already exist.
                        if (sharedNode)
                        {
                            continue;
                        }

                        // top level references to the type definition node were already added.
                        if (reference.TargetId == typeDefinition.NodeId)
                        {
                            continue;
                        }

                        // see if a reference is allowed.
                        if (!IsExternalReferenceAllowed(reference.ReferenceTypeId))
                        {
                            continue;
                        }

                        // add one way reference.
                        source.References.Add(reference.ReferenceTypeId, reference.IsInverse, reference.TargetId);
                        continue;
                    }
                                                                    
                    // add forward and backward reference.
                    AddReference(source, reference.ReferenceTypeId, reference.IsInverse, target, true);
                }
            }
        }