public static SwitchStatement Switch(SourceSpan span, SourceLocation header, Expression value, params SwitchCase[] cases)
        {
            Contract.RequiresNotNull(value, "value");
            Contract.Requires(value.Type == typeof(int), "value", "Value must be int");
            Contract.RequiresNotEmpty(cases, "cases");
            Contract.RequiresNotNullItems(cases, "cases");

            bool @default = false;
            int max = Int32.MinValue;
            int min = Int32.MaxValue;
            foreach (SwitchCase sc in cases) {
                if (sc.IsDefault) {
                    Contract.Requires(@default == false, "cases", "Only one default clause allowed");
                    @default = true;
                } else {
                    int val = sc.Value;
                    if (val > max) max = val;
                    if (val < min) min = val;
                }
            }

            Contract.Requires(UniqueCaseValues(cases, min, max), "cases", "Case values must be unique");

            return new SwitchStatement(span, header, value, CollectionUtils.ToReadOnlyCollection(cases));
        }
		public UseStatement (SourceLocation location, string module, bool relative = false)
			: base (location)
		{
			Module = module;
			Relative = relative;
			Imports = new List<string> ();
		}
Exemple #3
0
 internal SwitchCase(SourceLocation header, bool @default, int value, Statement body)
     : base(AstNodeType.SwitchCase) {
     _header = header;
     _default = @default;
     _value = value;
     _body = body;
 }
		public CaseExpression (SourceLocation location, AstNode pattern, AstNode condition, AstNode value)
			: base (location)
		{
			Children.Add (pattern);
			Children.Add (condition);
			Children.Add (value);
		}
 public Selector(string name, string parameter, SourceLocation sourceLocation, string afterTheParameter = null) {
     Name = name.Is() ? name : (parameter.Is() ? "*" : null);
     Parameter = parameter;
     SourceLocation = sourceLocation;
     AfterTheParameter = afterTheParameter;
     _hashCode = this.CreateHashCode(Name, Parameter);
 }
Exemple #6
0
		public TableContext(SourceLocation sourceLocation, Identifier remainingPart, Scope scope, TableBinding tableBinding, string correlationName)
			: base(sourceLocation, remainingPart)
		{
			_scope = scope;
			_tableBinding = tableBinding;
			_correlationName = correlationName;
		}
Exemple #7
0
        public void TestDiagnostic()
        {
            MockMessageProvider provider = new MockMessageProvider();
            SyntaxTree syntaxTree = new MockSyntaxTree();
            CultureInfo englishCulture = CultureHelpers.EnglishCulture;

            DiagnosticInfo di1 = new DiagnosticInfo(provider, 1);
            Assert.Equal(1, di1.Code);
            Assert.Equal(DiagnosticSeverity.Error, di1.Severity);
            Assert.Equal("MOCK0001", di1.MessageIdentifier);
            Assert.Equal("The first error", di1.GetMessage(englishCulture));

            DiagnosticInfo di2 = new DiagnosticInfo(provider, 1002, "Elvis", "Mort");
            Assert.Equal(1002, di2.Code);
            Assert.Equal(DiagnosticSeverity.Warning, di2.Severity);
            Assert.Equal("MOCK1002", di2.MessageIdentifier);
            Assert.Equal("The second warning about Elvis and Mort", di2.GetMessage(englishCulture));

            Location l1 = new SourceLocation(syntaxTree, new TextSpan(5, 8));
            var d1 = new CSDiagnostic(di2, l1);
            Assert.Equal(l1, d1.Location);
            Assert.Same(syntaxTree, d1.Location.SourceTree);
            Assert.Equal(new TextSpan(5, 8), d1.Location.SourceSpan);
            Assert.Equal(0, d1.AdditionalLocations.Count());
            Assert.Same(di2, d1.Info);
        }
Exemple #8
0
		public void SkipTo(SourceLocation tokenLocation)
		{
			if (Token.Range.StartLocation > tokenLocation)
			{
				// If the current token is after the requested position we cannot get
				// there so we are finished.
				
				return;
			}
			else if (Token.Range.StartLocation <= tokenLocation && tokenLocation <= Token.Range.EndLocation)
			{
				// In this case the current token is the searched one.

				return;
			}

			// Skip all tokens that end before the requested position

			do
			{
				if (!ReadNext())
					return;
			}
			while (Token.Range.EndLocation < tokenLocation);

			// The current token must contain the token pos. If the token starts after
			// the requested token pos that position is in the middle of two tokens.
			// In this case we return false.

			if (Token.Range.StartLocation >= tokenLocation)
				ReadPrevious();
		}
 public SourceLocationFoundEventArgs(object target, SourceLocation sourceLocation)
 {
     UnitTestUtility.Assert(target != null, "Target cannot be null and is ensured by caller");
     UnitTestUtility.Assert(sourceLocation != null, "Target cannot be null and is ensured by caller");
     this.target = target;
     this.sourceLocation = sourceLocation;
 }
Exemple #10
0
 public MappingLocation(SourceLocation location, int contentLength)
 {
     ContentLength = contentLength;
     AbsoluteIndex = location.AbsoluteIndex;
     LineIndex = location.LineIndex;
     CharacterIndex = location.CharacterIndex;
 }
Exemple #11
0
		public void CheckStatics()
		{
			SourceLocation min = new SourceLocation(0, 0);
			SourceLocation max = new SourceLocation(SourceLocation.MaxColumn, SourceLocation.MaxLine);
			Assert.AreEqual(min, SourceLocation.MinValue);
			Assert.AreEqual(max, SourceLocation.MaxValue);
		}
Exemple #12
0
 public ForeachNode(SourceLocation location, string variable, AstNode target, AstNode body)
 {
     this.SourceLocation = location;
     Variable = variable;
     Children.Add(target);
     Children.Add(body);
 }
        public void Resolve_CalculatesAssemblyLocationInLookupText(string lookupText, int assemblyLocation)
        {
            // Arrange
            var errorSink = new ErrorSink();
            var tagHelperDescriptorResolver = new InspectableTagHelperDescriptorResolver();
            var directiveType = TagHelperDirectiveType.AddTagHelper;
            var resolutionContext = new TagHelperDescriptorResolutionContext(
                new[]
                {
                    new TagHelperDirectiveDescriptor
                    {
                        DirectiveText = lookupText,
                        Location = SourceLocation.Zero,
                        DirectiveType = directiveType
                    }
                },
                errorSink);
            var expectedSourceLocation = new SourceLocation(assemblyLocation, 0, assemblyLocation);

            // Act
            tagHelperDescriptorResolver.Resolve(resolutionContext);

            // Assert
            Assert.Empty(errorSink.Errors);
            Assert.Equal(expectedSourceLocation, tagHelperDescriptorResolver.DocumentLocation);
        }
 public EnforcedAssignmentNode(SourceLocation location, string type, string variable, AstNode value)
 {
     this.SourceLocation = location;
     Type = type;
     Variable = variable;
     Children.Add(value);
 }
        /// <summary>
        /// Loads an <see cref="Assembly"/> using the given <paramref name="name"/> and resolves
        /// all valid <see cref="ITagHelper"/> <see cref="Type"/>s.
        /// </summary>
        /// <param name="name">The name of an <see cref="Assembly"/> to search.</param>
        /// <param name="documentLocation">The <see cref="SourceLocation"/> of the associated
        /// <see cref="Parser.SyntaxTree.SyntaxTreeNode"/> responsible for the current <see cref="Resolve"/> call.
        /// </param>
        /// <param name="errorSink">The <see cref="ErrorSink"/> used to record errors found when resolving
        /// <see cref="ITagHelper"/> <see cref="Type"/>s.</param>
        /// <returns>An <see cref="IEnumerable{Type}"/> of valid <see cref="ITagHelper"/> <see cref="Type"/>s.
        /// </returns>
        public IEnumerable<Type> Resolve(string name, 
                                         SourceLocation documentLocation, 
                                         [NotNull] ErrorSink errorSink)
        {
            if (string.IsNullOrEmpty(name))
            {
                errorSink.OnError(documentLocation,
                                  Resources.TagHelperTypeResolver_TagHelperAssemblyNameCannotBeEmptyOrNull);

                return Type.EmptyTypes;
            }

            var assemblyName = new AssemblyName(name);

            IEnumerable<TypeInfo> libraryTypes;
            try
            {
                libraryTypes = GetExportedTypes(assemblyName);
            }
            catch (Exception ex)
            {
                errorSink.OnError(
                    documentLocation,
                    Resources.FormatTagHelperTypeResolver_CannotResolveTagHelperAssembly(
                        assemblyName.Name,
                        ex.Message));

                return Type.EmptyTypes;
            }

            var validTagHelpers = libraryTypes.Where(IsTagHelper);

            // Convert from TypeInfo[] to Type[]
            return validTagHelpers.Select(type => type.AsType());
        }
		public BinaryExpression (SourceLocation location, BinaryOperation op, AstNode left, AstNode right)
			: base (location)
		{
			Operation = op;
			Add (left);
			Add (right);
		}
Exemple #17
0
        /// <summary>
        /// Render a helpful description of the location of the error in the GraphQL
        /// Source document.
        /// </summary>
        private static string highlightSourceAtLocation(Source source, SourceLocation location)
        {
            var line = location.Line;
            var prevLineNum = (line - 1).ToString();
            var lineNum = line.ToString();
            var nextLineNum = (line + 1).ToString();
            var padLen = nextLineNum.Length;
            var lines = _lineSplitter.Split(source.Body);
            var errorMessage = new StringBuilder();

            if (line >= 2)
            {
                errorMessage.AppendLine(prevLineNum.PadLeft(padLen, ' ') + ": " + lines[line - 2]);
            }
            else
            {
                errorMessage.AppendLine();
            }

            errorMessage.AppendLine(lineNum.PadLeft(padLen, ' ') + ": " + lines[line - 1]);
            errorMessage.AppendLine(new String(' ', padLen + location.Column) + "^");
            if (line < lines.Length)
            {
                errorMessage.AppendLine(nextLineNum.PadLeft(padLen, ' ') + ": " + lines[line]);
            }
            else
            {
                errorMessage.AppendLine();
            }

            return errorMessage.ToString();
        }
 public CodeBlockInfo(string name, SourceLocation start, bool isTopLevel, Span transitionSpan, Span initialSpan) {
     Name = name;
     Start = start;
     IsTopLevel = isTopLevel;
     TransitionSpan = transitionSpan;
     InitialSpan = initialSpan;
 }
		public MethodParameterInfoContext(SourceLocation sourceLocation, int parameterIndex, Scope scope, Type expressionType, Identifier methodName)
			: base(sourceLocation, parameterIndex)
		{
			_scope = scope;
			_expressionType = expressionType;
			_methodName = methodName;
		}
Exemple #20
0
        private static SourceLocation FindNearestLine(PdbFunction function, int ilOffset)
        {
            int distance = int.MaxValue;
            SourceLocation nearest = null;

            foreach (PdbSequencePointCollection sequenceCollection in function.SequencePoints)
            {
                foreach (PdbSequencePoint point in sequenceCollection.Lines)
                {
                    int dist = (int)Math.Abs(point.Offset - ilOffset);
                    if (dist < distance)
                    {
                        if (nearest == null)
                            nearest = new SourceLocation();

                        nearest.FilePath = sequenceCollection.File.Name;
                        nearest.LineNumber = (int)point.LineBegin;
                        nearest.LineNumberEnd = (int)point.LineEnd;
                        nearest.ColStart = (int)point.ColBegin;
                        nearest.ColEnd = (int)point.ColEnd;
                    }
                }
            }

            return nearest;
        }
Exemple #21
0
 public IfNode(SourceLocation location, AstNode predicate, AstNode body, AstNode elseBody)
 {
     this.SourceLocation = location;
     Children.Add(predicate);
     Children.Add(body);
     Children.Add(elseBody);
 }
Exemple #22
0
 public static CatchBlock Catch(SourceSpan span, SourceLocation header, Type type, Variable target, Statement body)
 {
     Contract.RequiresNotNull(type, "type");
     Contract.Requires(target == null || TypeUtils.CanAssign(target.Type, type), "target");
     Contract.RequiresNotNull(body, "body");
     return new CatchBlock(span, header, type, target, body);
 }
Exemple #23
0
 /// <summary>
 /// Called by <see cref="DoStatementBuilder"/>.
 /// </summary>
 internal DoStatement(SourceSpan span, SourceLocation header, Expression /*!*/ test, Statement /*!*/ body)
     : base(AstNodeType.DoStatement, span)
 {
     _header = header;
     _test = test;
     _body = body;
 }
 public FunctionCallNode(SourceLocation location, AstNode target, ArgumentListNode parameters, List<BinaryOperationNode> initialAttributes)
 {
     this.SourceLocation = location;
     Children.Add(target);
     Children.Add(parameters);
     InitialAttributes = initialAttributes;
 }
		public ForeachStatement (SourceLocation location, string item, AstNode iterator, AstNode body)
			: base (location)
		{
			this.Item = item;
			this.Add (iterator);
			this.Add (body);
		}
        public void WriterConstructedWithoutContentLengthAndSourceFile_AddsLinePragmas_OnDispose()
        {
            // Arrange
            var location = new SourceLocation(10, 1, 20);
            var expected = string.Join(Environment.NewLine,
                                       @"#line 2 ""myfile""",
                                       "Hello world",
                                       "",
                                       "#line default",
                                       "#line hidden",
                                       "");
            var expectedMappings = new LineMapping(
                                new MappingLocation(location, 30),
                                new MappingLocation(new SourceLocation(18, 1, 0), 11));
            var writer = new CSharpCodeWriter();

            // Act
            using (var mappingWriter = new CSharpLineMappingWriter(writer, location, "myfile"))
            {
                writer.Write("Hello world");
            }

            // Assert
            Assert.Equal(expected, writer.GenerateCode());
            Assert.Empty(writer.LineMappingManager.Mappings);
        }
 public static TryStatement TryCatchFinally(SourceSpan span, SourceLocation header, Statement body, CatchBlock[] handlers, Statement @finally)
 {
     return new TryStatement(
         span, header,
          body, CollectionUtils.ToReadOnlyCollection(handlers), @finally
     );
 }
 public TernaryOperationNode(SourceLocation location, AstNode predicate, AstNode trueStatement, AstNode falseStatement)
 {
     this.SourceLocation = location;
     Children.Add(predicate);
     Children.Add(trueStatement);
     Children.Add(falseStatement);
 }
Exemple #29
0
        public Selector(string selector,SourceLocation sourceLocation)  {
            AfterTheParameter = null;

            // parse up to the first square bracket.
            if (string.IsNullOrEmpty(selector)) {
                Name = string.Empty;
                Parameter = null;
            } else {
                selector = selector.TrimStart('.');
                var p = selector.IndexOf('[');
                var c = selector.IndexOf(']', p + 1);
                if (p == -1) {
                    Name = selector;
                    Parameter = null;
                } else {
                    Name = p == 0 ? "*" : selector.Substring(0, p);
                    p++;
                    Parameter = selector.Substring(p, c - p).Trim();
                    if(c < selector.Length) {
                        AfterTheParameter = selector.Substring(c + 1);
                    }
                    
                }
            }
            SourceLocation = sourceLocation;
            
            _hashCode = AfterTheParameter == null ? this.CreateHashCode(Name, Parameter) : this.CreateHashCode(Name,Parameter,AfterTheParameter);
        }
 public BinaryOperationNode(SourceLocation location, BinaryOperation operation, AstNode left, AstNode right)
 {
     this.SourceLocation = location;
     BinaryOperation = operation;
     Children.Add(left);
     Children.Add(right);
 }
Exemple #31
0
 protected void StartSymbol()
 {
     Buffer.Clear();
     CurrentStart = CurrentLocation;
     CurrentErrors.Clear();
 }
Exemple #32
0
 protected abstract TSymbol CreateSymbol(SourceLocation start, string content, TSymbolType type, IEnumerable <RazorError> errors);
 internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
 {
     _state.DefaultForceComplete(this, cancellationToken);
 }
        private Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> > MakeDeclaredBases(ConsList <TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics)
        {
            if (this.TypeKind == TypeKind.Enum)
            {
                // Handled by GetEnumUnderlyingType().
                return(new Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> >(null, ImmutableArray <NamedTypeSymbol> .Empty));
            }

            var reportedPartialConflict = false;

            Debug.Assert(basesBeingResolved == null || !basesBeingResolved.ContainsReference(this.OriginalDefinition));
            var newBasesBeingResolved = basesBeingResolved.Prepend(this.OriginalDefinition);
            var baseInterfaces        = ArrayBuilder <NamedTypeSymbol> .GetInstance();

            NamedTypeSymbol baseType         = null;
            SourceLocation  baseTypeLocation = null;

            var interfaceLocations = SpecializedSymbolCollections.GetPooledSymbolDictionaryInstance <NamedTypeSymbol, SourceLocation>();

            foreach (var decl in this.declaration.Declarations)
            {
                Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> > one = MakeOneDeclaredBases(newBasesBeingResolved, decl, diagnostics);
                if ((object)one == null)
                {
                    continue;
                }

                var partBase       = one.Item1;
                var partInterfaces = one.Item2;
                if (!reportedPartialConflict)
                {
                    if ((object)baseType == null)
                    {
                        baseType         = partBase;
                        baseTypeLocation = decl.NameLocation;
                    }
                    else if (baseType.TypeKind == TypeKind.Error && (object)partBase != null)
                    {
                        // if the old base was an error symbol, copy it to the interfaces list so it doesn't get lost
                        partInterfaces   = partInterfaces.Add(baseType);
                        baseType         = partBase;
                        baseTypeLocation = decl.NameLocation;
                    }
                    else if ((object)partBase != null && !TypeSymbol.Equals(partBase, baseType, TypeCompareKind.ConsiderEverything) && partBase.TypeKind != TypeKind.Error)
                    {
                        // the parts do not agree
                        if (partBase.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny))
                        {
                            if (containsOnlyOblivious(baseType))
                            {
                                baseType         = partBase;
                                baseTypeLocation = decl.NameLocation;
                                continue;
                            }
                            else if (containsOnlyOblivious(partBase))
                            {
                                continue;
                            }
                        }

                        var info = diagnostics.Add(ErrorCode.ERR_PartialMultipleBases, Locations[0], this);
                        baseType                = new ExtendedErrorTypeSymbol(baseType, LookupResultKind.Ambiguous, info);
                        baseTypeLocation        = decl.NameLocation;
                        reportedPartialConflict = true;
 public ContractDeclaration(SourceLocation location, string name, string doc)
     : base(location)
 {
     Name          = name;
     Documentation = doc;
 }
 public void ChangeStart(SourceLocation newStart)
 {
     Start = newStart;
 }
Exemple #37
0
 public TokenInfo(JSToken tokenKind, SourceLocation start, SourceLocation end)
 {
     TokenKind = tokenKind;
     Start     = start;
     End       = end;
 }
        internal static StackFrame CreateFrame(CorDebuggerSession session, CorFrame frame)
        {
            // TODO: Fix remaining.
            uint address = 0;
            //string typeFQN;
            //string typeFullName;
            string addressSpace = "";
            string file         = "";
            int    line         = 0;
            int    column       = 0;
            string method       = "";
            string lang         = "";
            string module       = "";
            string type         = "";
            bool   hasDebugInfo = false;
            bool   hidden       = false;
            bool   external     = true;

            if (frame.FrameType == CorFrameType.ILFrame)
            {
                if (frame.Function != null)
                {
                    module = frame.Function.Module.Name;
                    CorMetadataImport importer = new CorMetadataImport(frame.Function.Module);
                    MethodInfo        mi       = importer.GetMethodInfo(frame.Function.Token);
                    method       = mi.DeclaringType.FullName + "." + mi.Name;
                    type         = mi.DeclaringType.FullName;
                    addressSpace = mi.Name;

                    var sp = GetSequencePoint(session, frame);
                    if (sp != null)
                    {
                        line    = sp.StartLine;
                        column  = sp.StartColumn;
                        file    = sp.Document.URL;
                        address = (uint)sp.Offset;
                    }

                    if (session.IsExternalCode(file))
                    {
                        external = true;
                    }
                    else
                    {
                        if (session.Options.ProjectAssembliesOnly)
                        {
                            external = mi.GetCustomAttributes(true).Any(v =>
                                                                        v is System.Diagnostics.DebuggerHiddenAttribute ||
                                                                        v is System.Diagnostics.DebuggerNonUserCodeAttribute);
                        }
                        else
                        {
                            external = mi.GetCustomAttributes(true).Any(v =>
                                                                        v is System.Diagnostics.DebuggerHiddenAttribute);
                        }
                    }
                    hidden = mi.GetCustomAttributes(true).Any(v => v is System.Diagnostics.DebuggerHiddenAttribute);
                }
                lang         = "Managed";
                hasDebugInfo = true;
            }
            else if (frame.FrameType == CorFrameType.NativeFrame)
            {
                frame.GetNativeIP(out address);
                method = "<Unknown>";
                lang   = "Native";
            }
            else if (frame.FrameType == CorFrameType.InternalFrame)
            {
                switch (frame.InternalFrameType)
                {
                case CorDebugInternalFrameType.STUBFRAME_M2U:
                    method = "[Managed to Native Transition]";
                    break;

                case CorDebugInternalFrameType.STUBFRAME_U2M:
                    method = "[Native to Managed Transition]";
                    break;

                case CorDebugInternalFrameType.STUBFRAME_LIGHTWEIGHT_FUNCTION:
                    method = "[Lightweight Method Call]";
                    break;

                case CorDebugInternalFrameType.STUBFRAME_APPDOMAIN_TRANSITION:
                    method = "[Application Domain Transition]";
                    break;

                case CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL:
                    method = "[Function Evaluation]";
                    break;
                }
            }

            if (method == null)
            {
                method = "<Unknown>";
            }

            var loc = new SourceLocation(method, file, line, column);

            return(new StackFrame((long)address, addressSpace, loc, lang, external, hasDebugInfo, hidden, null, null));
        }
Exemple #39
0
        public async Task <GraphNode> AddNodeForSymbolAsync(ISymbol symbol, Project contextProject, Document contextDocument)
        {
            // Figure out what the location for this node should be. We'll arbitrarily pick the
            // first one, unless we have a contextDocument to restrict it
            var preferredLocation = symbol.Locations.FirstOrDefault(l => l.SourceTree != null);

            if (contextDocument != null)
            {
                var syntaxTree = await contextDocument.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);

                // If we have one in that tree, use it
                preferredLocation = symbol.Locations.FirstOrDefault(l => l.SourceTree == syntaxTree) ?? preferredLocation;
            }

            // We may need to look up source code within this solution
            if (preferredLocation == null && symbol.Locations.Any(loc => loc.IsInMetadata))
            {
                var newSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, contextProject.Solution, _cancellationToken).ConfigureAwait(false);

                if (newSymbol != null)
                {
                    preferredLocation = newSymbol.Locations.Where(loc => loc.IsInSource).FirstOrDefault();
                }
            }

            using (_gate.DisposableWait())
            {
                GraphNode node = await GetOrCreateNodeAsync(_graph, symbol, _solution, _cancellationToken).ConfigureAwait(false);

                node[RoslynGraphProperties.SymbolId]         = symbol.GetSymbolKey();
                node[RoslynGraphProperties.ContextProjectId] = GetContextProjectId(contextProject, symbol);
                node[RoslynGraphProperties.ExplicitInterfaceImplementations] = symbol.ExplicitInterfaceImplementations().Select(s => s.GetSymbolKey()).ToList();
                node[RoslynGraphProperties.DeclaredAccessibility]            = symbol.DeclaredAccessibility;
                node[RoslynGraphProperties.SymbolModifiers] = symbol.GetSymbolModifiers();
                node[RoslynGraphProperties.SymbolKind]      = symbol.Kind;

                if (contextDocument != null)
                {
                    node[RoslynGraphProperties.ContextDocumentId] = contextDocument.Id;
                }

                if (preferredLocation != null)
                {
                    var lineSpan       = preferredLocation.GetLineSpan();
                    var sourceLocation = new SourceLocation(
                        preferredLocation.SourceTree.FilePath,
                        new Position(lineSpan.StartLinePosition.Line, lineSpan.StartLinePosition.Character),
                        new Position(lineSpan.EndLinePosition.Line, lineSpan.EndLinePosition.Character));
                    node[CodeNodeProperties.SourceLocation] = sourceLocation;
                }

                // Keep track of this as a node we have added. Note this is a HashSet, so if the node was already added
                // we won't double-count.
                _createdNodes.Add(node);

                _nodeToSymbolMap[node]          = symbol;
                _nodeToContextProjectMap[node]  = contextProject;
                _nodeToContextDocumentMap[node] = contextDocument;

                return(node);
            }
        }
Exemple #40
0
 public IfStatement(SourceLocation location, Expression condition, BlockStatement body,
                    IEnumerable <ElseStatement> elses) : base(location, body)
 {
     this.Condition = condition;
     this.Elses     = elses.ToArray();
 }
Exemple #41
0
 public static HassiumString get_message(VirtualMachine vm, HassiumObject self, SourceLocation location, params HassiumObject[] args)
 {
     return(new HassiumString(string.Format("Variable Not Found: variable was not found inside the stack frmae")));
 }
Exemple #42
0
            public static HassiumString tostring(VirtualMachine vm, HassiumObject self, SourceLocation location, params HassiumObject[] args)
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine(get_message(vm, self, location).String);
                sb.Append(vm.UnwindCallStack());

                return(new HassiumString(sb.ToString()));
            }
Exemple #43
0
 public SoftDebuggerStackFrame(Mono.Debugger.Soft.StackFrame frame, string addressSpace, SourceLocation location, string language, bool isExternalCode, bool hasDebugInfo, bool isDebuggerHidden, string fullModuleName, string fullTypeName)
     : base(frame.ILOffset, addressSpace, location, language, isExternalCode, hasDebugInfo, isDebuggerHidden, fullModuleName, fullTypeName)
 {
     StackFrame = frame;
 }
Exemple #44
0
            public static HassiumVariableNotFoundException _new(VirtualMachine vm, HassiumObject self, SourceLocation location, params HassiumObject[] args)
            {
                HassiumVariableNotFoundException exception = new HassiumVariableNotFoundException();


                return(exception);
            }
        private ImmutableArray <TypeParameterSymbol> MakeTypeParameters(DiagnosticBag diagnostics)
        {
            if (declaration.Arity == 0)
            {
                return(ImmutableArray <TypeParameterSymbol> .Empty);
            }

            var typeParameterMismatchReported = false;
            var typeParameterNames            = new string[declaration.Arity];
            var typeParameterVarianceKeywords = new string[declaration.Arity];
            var parameterBuilders1            = new List <List <TypeParameterBuilder> >();

            foreach (var syntaxRef in this.SyntaxReferences)
            {
                var typeDecl   = (CSharpSyntaxNode)syntaxRef.GetSyntax();
                var syntaxTree = syntaxRef.SyntaxTree;

                TypeParameterListSyntax tpl;
                switch (typeDecl.Kind)
                {
                case SyntaxKind.ClassDeclaration:
                case SyntaxKind.StructDeclaration:
                case SyntaxKind.InterfaceDeclaration:
                    tpl = ((TypeDeclarationSyntax)typeDecl).TypeParameterList;
                    break;

                case SyntaxKind.DelegateDeclaration:
                    tpl = ((DelegateDeclarationSyntax)typeDecl).TypeParameterList;
                    break;

                case SyntaxKind.EnumDeclaration:
                default:
                    // there is no such thing as a generic enum, so code should never reach here.
                    throw ExceptionUtilities.UnexpectedValue(typeDecl.Kind);
                }

                var parameterBuilder = new List <TypeParameterBuilder>();
                parameterBuilders1.Add(parameterBuilder);
                int i = 0;
                foreach (var tp in tpl.Parameters)
                {
                    var name         = typeParameterNames[i];
                    var location     = new SourceLocation(tp.Identifier);
                    var varianceKind = typeParameterVarianceKeywords[i];
                    if (name == null)
                    {
                        name         = typeParameterNames[i] = tp.Identifier.ValueText;
                        varianceKind = typeParameterVarianceKeywords[i] = tp.VarianceKeyword.ValueText;
                        for (int j = 0; j < i; j++)
                        {
                            if (name == typeParameterNames[j])
                            {
                                typeParameterMismatchReported = true;
                                diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name);
                                goto next;
                            }
                        }

                        if (!ReferenceEquals(ContainingType, null))
                        {
                            var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name);
                            if ((object)tpEnclosing != null)
                            {
                                // Type parameter '{0}' has the same name as the type parameter from outer type '{1}'
                                diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType);
                            }
                        }
                        next :;
                    }
                    else if (!typeParameterMismatchReported)
                    {
                        // Note: the "this", below, refers to the name of the current class, which includes its type
                        // parameter names.  But the type parameter names have not been computed yet.  Therefore, we
                        // take advantage of the fact that "this" won't undergo "ToString()" until later, when the
                        // diagnostic is printed, by which time the type parameters field will have been filled in.
                        if (varianceKind != tp.VarianceKeyword.ValueText)
                        {
                            // Dev10 reports CS1067, even if names also don't match
                            typeParameterMismatchReported = true;
                            diagnostics.Add(
                                ErrorCode.ERR_PartialWrongTypeParamsVariance,
                                declaration.NameLocations.First(),
                                this); // see comment above
                        }
                        else if (name != tp.Identifier.ValueText)
                        {
                            typeParameterMismatchReported = true;
                            diagnostics.Add(
                                ErrorCode.ERR_PartialWrongTypeParams,
                                declaration.NameLocations.First(),
                                this); // see comment above
                        }
                    }
                    parameterBuilder.Add(new TypeParameterBuilder(syntaxTree.GetReference(tp), this, location));
                    i++;
                }
            }

            var parameterBuilders2 = parameterBuilders1.Transpose(); // type arguments are positional
            var parameters         = parameterBuilders2.Select((builders, i) => builders[0].MakeSymbol(i, builders, diagnostics));

            return(parameters.AsImmutable());
        }
Exemple #46
0
        internal MSAst.Expression /*!*/ AddDebugInfo(MSAst.Expression /*!*/ expression, SourceLocation start, SourceLocation end)
        {
            if (PyContext.PythonOptions.GCStress != null)
            {
                expression = Ast.Block(
                    Ast.Call(
                        typeof(GC).GetMethod("Collect", new[] { typeof(int) }),
                        Ast.Constant(PyContext.PythonOptions.GCStress.Value)
                        ),
                    expression
                    );
            }

            return(AstUtils.AddDebugInfo(expression, Document, start, end));
        }
Exemple #47
0
        protected void Start(string test)
        {
            TargetRuntime runtime;

            switch (EngineId)
            {
            case "MonoDevelop.Debugger.Win32":
                runtime = Runtime.SystemAssemblyService.GetTargetRuntime("MS.NET");
                break;

            case "Mono.Debugger.Soft":
                runtime = Runtime.SystemAssemblyService.GetTargetRuntimes()
                          .OfType <MonoTargetRuntime> ()
                          .OrderByDescending((o) => {
                    //Attempt to find latest version of Mono registred in IDE and use that for unit tests
                    if (string.IsNullOrWhiteSpace(o.Version) || o.Version == "Unknown")
                    {
                        return(new Version(0, 0, 0, 0));
                    }
                    int indexOfBeforeDetails = o.Version.IndexOf(" (", StringComparison.Ordinal);
                    if (indexOfBeforeDetails == -1)
                    {
                        return(new Version(0, 0, 0, 0));
                    }
                    string hopefullyVersion = o.Version.Remove(indexOfBeforeDetails);
                    Version version;
                    if (Version.TryParse(hopefullyVersion, out version))
                    {
                        return(version);
                    }
                    else
                    {
                        return(new Version(0, 0, 0, 0));
                    }
                }).FirstOrDefault();
                break;

            default:
                runtime = Runtime.SystemAssemblyService.DefaultRuntime;
                break;
            }

            if (runtime == null)
            {
                Assert.Ignore("Runtime not found for: {0}", EngineId);
                return;
            }

            Console.WriteLine("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version + " " + (IntPtr.Size == 8 ? "64bit" : "32bit"));

            // main/build/tests
            FilePath path = Path.GetDirectoryName(GetType().Assembly.Location);
            var      exe  = Path.Combine(path, "MonoDevelop.Debugger.Tests.TestApp.exe");

            var cmd = new DotNetExecutionCommand();

            cmd.TargetRuntime = runtime;
            cmd.Command       = exe;
            cmd.Arguments     = test;

            if (Platform.IsWindows)
            {
                var monoRuntime = runtime as MonoTargetRuntime;
                if (monoRuntime != null)
                {
                    var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command);
                    psi.UseShellExecute = false;
                    psi.CreateNoWindow  = true;
                    System.Diagnostics.Process.Start(psi).WaitForExit();
                }
            }

            var dsi  = engine.CreateDebuggerStartInfo(cmd);
            var soft = dsi as SoftDebuggerStartInfo;

            if (soft != null)
            {
                var assemblyName = AssemblyName.GetAssemblyName(exe);

                soft.UserAssemblyNames = new List <AssemblyName> ();
                soft.UserAssemblyNames.Add(assemblyName);
            }

            Session = engine.CreateSession();
            var ops = new DebuggerSessionOptions();

            ops.ProjectAssembliesOnly = true;
            ops.EvaluationOptions     = EvaluationOptions.DefaultOptions;
            ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
            ops.EvaluationOptions.EvaluationTimeout = 100000;

            path       = path.ParentDirectory.ParentDirectory.Combine("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath;
            SourceFile = TextFile.ReadFile(path);
            TestName   = test;
            AddBreakpoint("break");

            var done = new ManualResetEvent(false);

            Session.TargetHitBreakpoint += (sender, e) => {
                Frame = e.Backtrace.GetFrame(0);
                lastStoppedPosition = Frame.SourceLocation;
                targetStoppedEvent.Set();
                done.Set();
            };

            Session.TargetExceptionThrown += (sender, e) => {
                Frame = e.Backtrace.GetFrame(0);
                for (int i = 0; i < e.Backtrace.FrameCount; i++)
                {
                    if (!e.Backtrace.GetFrame(i).IsExternalCode)
                    {
                        Frame = e.Backtrace.GetFrame(i);
                        break;
                    }
                }
                lastStoppedPosition = Frame.SourceLocation;
                targetStoppedEvent.Set();
            };

            Session.TargetStopped += (sender, e) => {
                //This can be null in case of ForcedStop
                //which is called when exception is thrown
                //when Continue & Stepping is executed
                if (e.Backtrace != null)
                {
                    Frame = e.Backtrace.GetFrame(0);
                    lastStoppedPosition = Frame.SourceLocation;
                    targetStoppedEvent.Set();
                }
                else
                {
                    Console.WriteLine("e.Backtrace is null");
                }
            };

            var targetExited = new ManualResetEvent(false);

            Session.TargetExited += delegate {
                targetExited.Set();
            };

            Session.Run(dsi, ops);
            Session.ExceptionHandler = (ex) => {
                Console.WriteLine("Session.ExceptionHandler:" + Environment.NewLine + ex.ToString());
                return(true);
            };
            switch (WaitHandle.WaitAny(new WaitHandle[] { done, targetExited }, 30000))
            {
            case 0:
                //Breakpoint is hit good... run tests now
                break;

            case 1:
                throw new Exception("Test application exited before hitting breakpoint");

            default:
                throw new Exception("Timeout while waiting for initial breakpoint");
            }
            if (Session is SoftDebuggerSession)
            {
                Console.WriteLine("SDB protocol version:" + ((SoftDebuggerSession)Session).ProtocolVersion);
            }
        }
Exemple #48
0
 protected PatternNode(SourceLocation location) : base(location)
 {
 }
Exemple #49
0
 public string ToUrl(SourceLocation location) => location != null?GetFileById(location.Id).Url : "";
 protected void RunSourceLocationTest(string input, SourceLocation expected, int checkAt = 0)
 {
     RunSourceLocationTest(input, expected, r => AdvanceReader(checkAt, r));
 }
 public HtmlSymbol(SourceLocation start, string content, HtmlSymbolType type)
     : base(start, content, type, Enumerable.Empty <RazorError>())
 {
 }
 public HtmlSymbol(SourceLocation start, string content, HtmlSymbolType type, IEnumerable <RazorError> errors)
     : base(start, content, type, errors)
 {
 }
        internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, DiagnosticBag diagnostics, out bool modifierErrors)
        {
            DeclarationModifiers defaultAccess =
                (containingType.IsInterface) ? DeclarationModifiers.Public : DeclarationModifiers.Private;

            DeclarationModifiers allowedModifiers =
                DeclarationModifiers.AccessibilityMask |
                DeclarationModifiers.Const |
                DeclarationModifiers.New |
                DeclarationModifiers.Static |
                DeclarationModifiers.Fixed |
                DeclarationModifiers.Unsafe |
                DeclarationModifiers.Abstract; // filtered out later

            var errorLocation           = new SourceLocation(firstIdentifier);
            DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers(false, modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors);

            if ((result & DeclarationModifiers.Abstract) != 0)
            {
                diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation);
                result &= ~DeclarationModifiers.Abstract;
            }

            if ((result & DeclarationModifiers.Fixed) != 0)
            {
                if ((result & DeclarationModifiers.Static) != 0)
                {
                    // The modifier 'static' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.StaticKeyword));
                }

                if ((result & DeclarationModifiers.Const) != 0)
                {
                    // The modifier 'const' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ConstKeyword));
                }

                result &= ~(DeclarationModifiers.Static | DeclarationModifiers.Immutable | DeclarationModifiers.Const);
                Debug.Assert((result & ~(DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.New)) == 0);
            }


            if ((result & DeclarationModifiers.Const) != 0)
            {
                if ((result & DeclarationModifiers.Static) != 0)
                {
                    // The constant '{0}' cannot be marked static
                    diagnostics.Add(ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText);
                }

                if ((result & DeclarationModifiers.Unsafe) != 0)
                {
                    // The modifier 'unsafe' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword));
                }

                result |= DeclarationModifiers.Static; // "constants are considered static members"
            }
            else
            {
                // NOTE: always cascading on a const, so suppress.
                // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol
                // to determine whether or not unsafe is allowed.  Since this symbol and the containing type are
                // in the same compilation, it won't make a difference.  We do, however, have to pass the error
                // location explicitly.
                containingType.CheckUnsafeModifier(result, errorLocation, diagnostics);
            }

            return(result);
        }
Exemple #54
0
 public AutoTypeExpressionNode(SourceLocation location, TypeExpressionNode @class) : base(location)
 {
     Class = @class;
 }
Exemple #55
0
        public StringNode(SourceLocation location, string _string)
        {
            SourceLocation = location;

            String = _string;
        }
Exemple #56
0
        internal static MSAst.Expression TransformMaybeSingleLineSuite(Statement body, SourceLocation prevStart)
        {
            if (body.GlobalParent.IndexToLocation(body.StartIndex).Line != prevStart.Line)
            {
                return(body);
            }

            MSAst.Expression res = body.Reduce();

            res = RemoveDebugInfo(prevStart.Line, res);

            if (res.Type != typeof(void))
            {
                res = AstUtils.Void(res);
            }

            return(res);
        }
 public static string GetLocation(SourceLocation location)
 {
     return(string.Format("{0}:{1}:{2}", location.SourceFileName, location.StartingLineNumber, location.StartingColumnNumber));
 }
 public IndexerExpression(SourceLocation location, AstNode lvalue, AstNode index)
     : base(location)
 {
     Target = lvalue;
     Index  = index;
 }
 public void OffsetStart(SourceLocation documentStart)
 {
     Start = documentStart + Start;
 }
Exemple #60
0
        internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
        {
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var incompletePart = _state.NextIncompletePart;
                switch (incompletePart)
                {
                case CompletionPart.Attributes:
                    GetAttributes();
                    break;

                case CompletionPart.StartValidatingReferencedAssemblies:
                {
                    DiagnosticBag diagnostics = null;

                    if (AnyReferencedAssembliesAreLinked)
                    {
                        diagnostics = DiagnosticBag.GetInstance();
                        ValidateLinkedAssemblies(diagnostics, cancellationToken);
                    }

                    if (_state.NotePartComplete(CompletionPart.StartValidatingReferencedAssemblies))
                    {
                        if (diagnostics != null)
                        {
                            _assemblySymbol.DeclaringCompilation.DeclarationDiagnostics.AddRange(diagnostics);
                        }

                        _state.NotePartComplete(CompletionPart.FinishValidatingReferencedAssemblies);
                    }

                    if (diagnostics != null)
                    {
                        diagnostics.Free();
                    }
                }
                break;

                case CompletionPart.FinishValidatingReferencedAssemblies:
                    // some other thread has started validating references (otherwise we would be in the case above) so
                    // we just wait for it to both finish and report the diagnostics.
                    Debug.Assert(_state.HasComplete(CompletionPart.StartValidatingReferencedAssemblies));
                    _state.SpinWaitComplete(CompletionPart.FinishValidatingReferencedAssemblies, cancellationToken);
                    break;

                case CompletionPart.MembersCompleted:
                    this.GlobalNamespace.ForceComplete(locationOpt, cancellationToken);

                    if (this.GlobalNamespace.HasComplete(CompletionPart.MembersCompleted))
                    {
                        _state.NotePartComplete(CompletionPart.MembersCompleted);
                    }
                    else
                    {
                        Debug.Assert(locationOpt != null, "If no location was specified, then the namespace members should be completed");
                        return;
                    }

                    break;

                case CompletionPart.None:
                    return;

                default:
                    // any other values are completion parts intended for other kinds of symbols
                    _state.NotePartComplete(incompletePart);
                    break;
                }

                _state.SpinWaitComplete(incompletePart, cancellationToken);
            }
        }