Exemple #1
0
 internal override void Read(NetIncomingMessage Message)
 {
     base.Read(Message);
     Language = (CodeLanguage)Enum.Parse(typeof(CodeLanguage), Message.ReadString());
     Location = (CodeLocation)Enum.Parse(typeof(CodeLocation), Message.ReadString());
     Source = Message.ReadString();
 }
        /// <summary>
        /// Initializes a new instance of the Whitespace class.
        /// </summary>
        /// <param name="text">The whitespace text.</param>
        /// <param name="location">The location of the whitespace in the code.</param>
        /// <param name="parent">The parent code unit.</param>
        /// <param name="generated">True if the token is inside of a block of generated code.</param>
        internal Whitespace(
            string text,
            CodeLocation location,
            Reference<ICodePart> parent,
            bool generated)
            : base(text,
            CsTokenType.WhiteSpace,
            CsTokenClass.Whitespace,
            location,
            parent,
            generated)
        {
            Param.AssertValidString(text, "text");
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(parent, "parent");
            Param.Ignore(generated);

            for (int i = 0; i < text.Length; ++i)
            {
                if (text[i] == ' ')
                {
                    ++this.spaceCount;
                }
                else if (text[i] == '\t')
                {
                    ++this.tabCount;
                }
            }
        }
        static DToken SearchBackward(TextDocument doc, int caretOffset, CodeLocation caret,out DToken lastToken)
        {
            var ttp = doc.GetText(0, caretOffset);
            var sr = new StringReader(ttp);
            var lexer = new Lexer(sr);
            lexer.NextToken();

            var stk=new Stack<DToken>();

            while (lexer.LookAhead.Kind!=DTokens.EOF)
            {
                if (lexer.LookAhead.Kind == DTokens.OpenParenthesis || lexer.LookAhead.Kind==DTokens.OpenSquareBracket || lexer.LookAhead.Kind==DTokens.OpenCurlyBrace)
                    stk.Push(lexer.LookAhead);

                else if (lexer.LookAhead.Kind == DTokens.CloseParenthesis || lexer.LookAhead.Kind == DTokens.CloseSquareBracket || lexer.LookAhead.Kind == DTokens.CloseCurlyBrace)
                {
                    if (stk.Peek().Kind == getOppositeBracketToken( lexer.LookAhead.Kind))
                        stk.Pop();
                }

                lexer.NextToken();
            }

            lastToken = lexer.CurrentToken;

            sr.Close();
            lexer.Dispose();

            if (stk.Count < 1)
                return null;

            return stk.Pop();
        }
Exemple #4
0
		public ParserError(bool IsSemanticError, string Message, int KeyToken, CodeLocation ErrorLocation)
		{
			IsSemantic = IsSemanticError;
			this.Message = Message;
			this.Token = KeyToken;
			this.Location = ErrorLocation;
		}
 public void Constructor(string filename, int line, int column)
 {
     var location = new CodeLocation(filename, line, column);
     Assert.AreEqual(filename, location.Path);
     Assert.AreEqual(line, location.Line);
     Assert.AreEqual(column, location.Column);
 }
        public static BracketSearchResult SearchBrackets(TextDocument doc, int caretOffset, TextLocation caret)
        {
            var caretLocation = new CodeLocation(caret.Column, caret.Line);
            try
            {
                if (caretOffset < 1 || caretOffset>=doc.TextLength-2)
                    return null;

                // Search backward
                DToken lastToken=null;
                var tk_start = SearchBackward(doc, caretOffset, caretLocation,out lastToken);

                if (tk_start == null)
                    return null;

                // Search forward
                var tk_end = SearchForward(doc,
                    doc.GetOffset(lastToken.EndLocation.Line,lastToken.EndLocation.Column),
                    lastToken.EndLocation,
                    getOppositeBracketToken(tk_start.Kind));

                if (tk_end == null)
                    return null;

                int start = doc.GetOffset(tk_start.Location.Line, tk_start.Location.Column),
                    end = doc.GetOffset(tk_end.Location.Line, tk_end.Location.Column);

                return new BracketSearchResult(start, 1, end, 1);
            }
            catch { return null; }
        }
 public EVException([CallerFilePath] string callerFilePath = "",
                    [CallerLineNumber] int callerLineNumber = 0, 
                    [CallerMemberName] string callerMemberName = "")
 {
     CodeLocation codeLocation = new CodeLocation(callerFilePath, callerLineNumber, callerMemberName);
     this.AddNamedProperty("EVExceptionConstructionLocation", codeLocation.ToString());
 }
Exemple #8
0
        public IEnumerable<DMethod> FindFitting(ResolverContextStack ctxt, CodeLocation currentLocation, ISemantic firstArgument, string nameFilter = null)
        {
            if (IsProcessing)
                return null;

            var preMatchList = new List<DMethod>();

            bool dontUseNameFilter = nameFilter == null;

            lock(CachedMethods)
                foreach (var kv in CachedMethods)
                {
                    // First test if arg is matching the parameter
                    if ((dontUseNameFilter || kv.Key.Name == nameFilter) &&
                        ResultComparer.IsImplicitlyConvertible(firstArgument, kv.Value, ctxt))
                        preMatchList.Add(kv.Key);
                }

            // Then filter out methods which cannot be accessed in the current context
            // (like when the method is defined in a module that has not been imported)
            var mv = new MatchFilterVisitor<DMethod>(ctxt, preMatchList);

            mv.IterateThroughScopeLayers(currentLocation);

            return mv.filteredList;
        }
Exemple #9
0
        public void ForStatement()
        {
            var code = @"module A; // 1
            void main(){
            for(
            int
            i= // 5
            0;
            i<100;
            i++)

            { // 10
            }";
            var mod = DParser.ParseString(code);
            var main = mod["main"].First() as DMethod;

            var l = new CodeLocation(1,4);
            var off = DocumentHelper.LocationToOffset(code,l);
            ParserTrackerVariables ptr;
            CodeLocation caretLoc;
            //var parsedBlock = AbstractCompletionProvider.FindCurrentCaretContext(code,main, off,l,out ptr, out caretLoc);

            /*
             * a) Test if completion popup would open in each code situation
             * b) Test in which case iteration variables can be found.
             */

            //TODO
        }
Exemple #10
0
        public ISyntaxRegion GetNextMetaBlockOrStatStmt(CodeLocation until)
        {
            if (nextStatStmt == null && StaticStatementEnum != null) {
                if (StaticStatementEnum.MoveNext ())
                    nextStatStmt = StaticStatementEnum.Current;
                else
                    StaticStatementEnum = null;
            }
            if (nextMetaDecl == null && MetaBlockEnum != null) {
                if (MetaBlockEnum.MoveNext ())
                    nextMetaDecl = MetaBlockEnum.Current;
                else
                    MetaBlockEnum = null;
            }

            ISyntaxRegion sr;

            if (nextStatStmt != null) {
                if (nextMetaDecl == null)
                    sr = nextStatStmt;
                else
                    sr = nextStatStmt.First (nextMetaDecl);
            } else if (nextMetaDecl != null)
                sr = nextMetaDecl;
            else
                return null;

            return sr.Location < until ? sr : null;
        }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance of the Argument class.
        /// </summary>
        /// <param name="name">The optional name of the argument.</param>
        /// <param name="modifiers">Modifers applied to this argument.</param>
        /// <param name="argumentExpression">The expression that forms the body of the argument.</param>
        /// <param name="location">The location of the argument in the code.</param>
        /// <param name="parent">The parent code part.</param>
        /// <param name="tokens">The tokens that form the argument.</param>
        /// <param name="generated">Indicates whether the argument is located within a block of generated code.</param>
        internal Argument(
            CsToken name, 
            ParameterModifiers modifiers, 
            Expression argumentExpression,
            CodeLocation location, 
            Reference<ICodePart> parent,
            CsTokenList tokens, 
            bool generated)
        {
            Param.Ignore(name);
            Param.Ignore(modifiers);
            Param.AssertNotNull(argumentExpression, "argumentExpression");
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(parent, "parent");
            Param.Ignore(tokens);
            Param.Ignore(generated);

            this.name = name;
            this.modifiers = modifiers;
            this.argumentExpression = argumentExpression;
            this.location = location;
            this.parent = parent;
            this.tokens = tokens;
            this.generated = generated;
        }
Exemple #12
0
		public void Set(IBlockNode b, CodeLocation caret)
		{
			scopedBlock = b;
			Caret = caret;
			
			ConditionalCompilation.EnumConditions(DeclarationCondititons, b, ctxt, caret); 
		}
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the ParamsToken class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal ParamsToken(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, TokenType.Params, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
 /// <summary>
 /// Initializes a new instance of the BitwiseComplementOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal BitwiseComplementOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Unary, OperatorType.BitwiseComplement, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
 /// <summary>
 /// Initializes a new instance of the LogicalAndOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal LogicalAndOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Logical, OperatorType.LogicalAnd, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
 /// <summary>
 /// Initializes a new instance of the XorEqualsOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal XorEqualsOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Assignment, OperatorType.XorEquals, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
 /// <summary>
 /// Initializes a new instance of the ConditionalQuestionMarkOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal ConditionalQuestionMarkOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Conditional, OperatorType.ConditionalQuestionMark, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
			public ConditionVisitor(ConditionSet cs,ResolutionContext ctxt, CodeLocation caret)
			{
				this.caret = caret;
				this.cs = cs;
				this.ctxt = ctxt;
				this.l = new MutableConditionFlagSet();
				cs.LocalFlags = l;
			}
Exemple #19
0
        /// <summary>
        /// Initializes a new instance of the SimpleToken class.
        /// </summary>
        /// <param name="document">The parent document.</param>
        /// <param name="text">The token string.</param>
        /// <param name="tokenType">The token type.</param>
        /// <param name="location">The location of the token within the code document.</param>
        /// <param name="generated">True if the token is inside of a block of generated code.</param>
        internal SimpleToken(CsDocument document, string text, int tokenType, CodeLocation location, bool generated)
            : base(new CodeUnitProxy(document), tokenType, location)
        {
            Param.Ignore(document, text, tokenType, location, generated);

            this.Text = text;
            this.Generated = generated;
        }
 /// <summary>
 /// Initializes a new instance of the RegionDirective class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The line text.</param>
 /// <param name="location">The location of the preprocessor in the code.</param>
 /// <param name="generated">Indicates whether the preprocessor lies within a block of generated code.</param>
 internal RegionDirective(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, PreprocessorType.Region, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
Exemple #21
0
 public Comment(Type commentType, string comment, bool commentStartsLine, CodeLocation startPosition, CodeLocation endPosition)
 {
     this.CommentType = commentType;
     this.CommentText = comment;
     this.CommentStartsLine = commentStartsLine;
     this.StartPosition = startPosition;
     this.EndPosition = endPosition;
 }
 /// <summary>
 /// Initializes a new instance of the MultiplicationOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal MultiplicationOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Arithmetic, OperatorType.Multiplication, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
Exemple #23
0
        /// <summary>
        /// Inserts import statement into correct place
        /// </summary>
        static void ApplySolution(string import, Document doc)
        {
            var eData = DResolverWrapper.GetEditorData(doc);
            var loc = new CodeLocation(0, DParser.FindLastImportStatementEndLocation(eData.SyntaxTree, eData.ModuleCode).Line + 1);
            doc.Editor.Insert(doc.Editor.GetLine(loc.Line).Offset, import.Trim() + doc.Editor.EolMarker);

            //IOInterface.InsertIntoCode(loc, "import " + mod.ModuleName + ";\n");
        }
Exemple #24
0
 /// <summary>
 /// Initializes a new instance of the ElementHeaderLine class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal ElementHeaderLine(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, CommentType.ElementHeaderLine, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
Exemple #25
0
        public static List<AbstractType> SearchAndResolve(ResolutionContext ctxt, CodeLocation caret, int nameHash, ISyntaxRegion idObject=null)
        {
            var scan = new NameScan(ctxt, nameHash, idObject);

            scan.IterateThroughScopeLayers(caret);

            return scan.matches_types;
        }
 /// <summary>
 /// Initializes a new instance of the PointerOperator class.
 /// </summary>
 /// <param name="document">The parent document.</param>
 /// <param name="text">The text of the item.</param>
 /// <param name="location">The location of the item.</param>
 /// <param name="generated">Indicates whether the item is generated.</param>
 internal PointerOperator(CsDocument document, string text, CodeLocation location, bool generated)
     : base(document, text, OperatorCategory.Reference, OperatorType.Pointer, location, generated)
 {
     Param.AssertNotNull(document, "document");
     Param.AssertValidString(text, "text");
     Param.AssertNotNull(location, "location");
     Param.Ignore(generated);
 }
Exemple #27
0
        public static EditorData CreateEditorData(Document EditorDocument, DModule Ast, CodeCompletionContext ctx, char triggerChar = '\0')
        {
            bool removeChar = char.IsLetter(triggerChar) || triggerChar == '_';

            var deltaOffset = 0;//removeChar ? 1 : 0;

            var caretOffset = ctx.TriggerOffset - (removeChar ? 1 : 0);
            var caretLocation = new CodeLocation(ctx.TriggerLineOffset - deltaOffset, ctx.TriggerLine);
            var codeCache = CreateCacheList(EditorDocument);

            var ed = new EditorData
            {
                CaretLocation = caretLocation,
                CaretOffset = caretOffset,
                ModuleCode = removeChar ? EditorDocument.Editor.Text.Remove(ctx.TriggerOffset - 1, 1) : EditorDocument.Editor.Text,
                SyntaxTree = Ast,
                ParseCache = codeCache
            };

            if (EditorDocument.HasProject)
            {
                var cfg = EditorDocument.Project.GetConfiguration(IdeApp.Workspace.ActiveConfiguration);

                if (cfg is DProjectConfiguration)
                {
                    var dcfg = cfg as DProjectConfiguration;
                    ed.GlobalDebugIds = dcfg.CustomDebugIdentifiers;
                    ed.IsDebug = dcfg.DebugMode;
                    ed.DebugLevel = dcfg.DebugLevel;
                    ed.GlobalVersionIds = dcfg.GlobalVersionIdentifiers;
                    double d;
                    ulong v;
                    if (Double.TryParse(EditorDocument.Project.Version, out d))
                        ed.VersionNumber = (ulong)d;
                    else if (UInt64.TryParse(EditorDocument.Project.Version, out v))
                        ed.VersionNumber = v;
                }
                else if (cfg is DubProjectConfiguration)
                {
                    var versions = new List<string>(VersionIdEvaluation.GetOSAndCPUVersions());

                    var dcfg = cfg as DubProjectConfiguration;
                    ed.IsDebug = dcfg.DebugMode;

                    HandleDubSettingsConditionExtraction(versions, (dcfg.ParentItem as DubProject).CommonBuildSettings);
                    HandleDubSettingsConditionExtraction(versions, dcfg.BuildSettings);

                    ed.GlobalVersionIds = versions.ToArray();
                }
            }

            if (ed.GlobalVersionIds == null)
            {
                ed.GlobalVersionIds = VersionIdEvaluation.GetOSAndCPUVersions();
            }

            return ed;
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the Token class.
        /// </summary>
        /// <param name="proxy">Proxy object for the token.</param>
        /// <param name="tokenType">The token type.</param>
        /// <param name="location">The location of the code unit.</param>
        internal Token(CodeUnitProxy proxy, int tokenType, CodeLocation location)
            : base(proxy, tokenType, location)
        {
            Param.Ignore(tokenType);
            Param.AssertNotNull(proxy, "proxy");
            Param.Ignore(location);

            CsLanguageService.Debug.Assert(System.Enum.IsDefined(typeof(TokenType), this.TokenType), "The type is invalid.");
        }
        public static void GenerateActivityPluginCode(CodeLocation codeLocation, PluginManager pluginManager,
            ICodeBlock codeBlock, IElement element)
        {

            foreach (ComponentPluginPair cpp in GetPluginsIn(pluginManager, codeLocation))
            {
                GenerateWithException(cpp.Generator.GenerateActivity, codeBlock, element, cpp.Plugin, pluginManager);
            }
        }
 /// <summary>
 /// Initializes a new instance of the GenericType class.
 /// </summary>
 /// <param name="childTokens">
 /// The list of child tokens that form the generic token.
 /// </param>
 /// <param name="location">
 /// The location of the generic in the code.
 /// </param>
 /// <param name="parent">
 /// The parent of the token.
 /// </param>
 /// <param name="generated">
 /// True if the token is inside of a block of generated code.
 /// </param>
 internal GenericType(MasterList<CsToken> childTokens, CodeLocation location, Reference<ICodePart> parent, bool generated)
     : base(childTokens, location, parent, CsTokenClass.GenericType, generated)
 {
     Param.AssertNotNull(childTokens, "childTokens");
     Param.AssertGreaterThanOrEqualTo(childTokens.Count, 3, "childTokens");
     Param.AssertNotNull(location, "location");
     Param.AssertNotNull(parent, "parent");
     Param.Ignore(generated);
 }
        /// <returns>Either CurrentScope, a BlockStatement object that is associated with the parent method or a complete new DModule object</returns>
        public static object FindCurrentCaretContext(string code,
                                                     IBlockNode CurrentScope,
                                                     int caretOffset, CodeLocation caretLocation,
                                                     out ParserTrackerVariables TrackerVariables)
        {
            bool ParseDecl = false;

            int blockStart         = 0;
            var blockStartLocation = CurrentScope.BlockStartLocation;

            if (CurrentScope is DMethod)
            {
                var block = (CurrentScope as DMethod).GetSubBlockAt(caretLocation);

                if (block != null)
                {
                    blockStart = DocumentHelper.LocationToOffset(code, blockStartLocation = block.Location);
                }
                else
                {
                    return(FindCurrentCaretContext(code, CurrentScope.Parent as IBlockNode, caretOffset, caretLocation, out TrackerVariables));
                }
            }
            else if (CurrentScope != null)
            {
                if (CurrentScope.BlockStartLocation.IsEmpty || caretLocation < CurrentScope.BlockStartLocation && caretLocation > CurrentScope.Location)
                {
                    ParseDecl  = true;
                    blockStart = DocumentHelper.LocationToOffset(code, blockStartLocation = CurrentScope.Location);
                }
                else
                {
                    blockStart = DocumentHelper.LocationToOffset(code, CurrentScope.BlockStartLocation);
                }
            }

            if (blockStart >= 0 && caretOffset - blockStart > 0)
            {
                var codeToParse = code.Substring(blockStart, caretOffset - blockStart);

                var sr  = new StringReader(codeToParse);
                var psr = DParser.Create(sr);

                /* Deadly important! For correct resolution behaviour,
                 * it is required to set the parser virtually to the blockStart position,
                 * so that everything using the returned object is always related to
                 * the original code file, not our code extraction!
                 */
                psr.Lexer.SetInitialLocation(blockStartLocation);

                object ret = null;

                if (CurrentScope == null || CurrentScope is IAbstractSyntaxTree)
                {
                    ret = psr.Parse();
                }
                else if (CurrentScope is DMethod)
                {
                    psr.Step();
                    ret = psr.BlockStatement(CurrentScope);
                }
                else if (CurrentScope is DModule)
                {
                    ret = psr.Root();
                }
                else
                {
                    psr.Step();
                    if (ParseDecl)
                    {
                        var ret2 = psr.Declaration(CurrentScope);

                        if (ret2 != null && ret2.Length > 0)
                        {
                            ret = ret2[0];
                        }
                    }
                    else
                    {
                        DBlockNode bn = null;
                        if (CurrentScope is DClassLike)
                        {
                            var t = new DClassLike((CurrentScope as DClassLike).ClassType);
                            t.AssignFrom(CurrentScope);
                            bn = t;
                        }
                        else if (CurrentScope is DEnum)
                        {
                            var t = new DEnum();
                            t.AssignFrom(CurrentScope);
                            bn = t;
                        }

                        bn.Clear();

                        psr.ClassBody(bn);
                        ret = bn;
                    }
                }

                TrackerVariables = psr.TrackerVariables;
                sr.Close();

                return(ret);
            }

            TrackerVariables = null;

            return(null);
        }
Exemple #32
0
 public IDisposable Push(INode newScope, CodeLocation caret)
 {
     return(Push_(newScope, caret) ? new PopDisposable(this) : null);
 }
Exemple #33
0
        /// <summary>
        /// Initializes a new instance of the OperatorSymbol class.
        /// </summary>
        /// <param name="text">
        /// The text of the operator symbol.
        /// </param>
        /// <param name="category">
        /// The category of the operator.
        /// </param>
        /// <param name="symbolType">
        /// The specific symbol type.
        /// </param>
        /// <param name="location">
        /// The location of the operator symbol in the code document.
        /// </param>
        /// <param name="parent">
        /// Reference to the parent code part.
        /// </param>
        /// <param name="generated">
        /// Indicates whether the operator lies within a block of generated code.
        /// </param>
        internal OperatorSymbol(string text, OperatorCategory category, OperatorType symbolType, CodeLocation location, Reference <ICodePart> parent, bool generated)
            : base(text, CsTokenType.OperatorSymbol, CsTokenClass.OperatorSymbol, location, parent, generated)
        {
            Param.AssertValidString(text, "text");
            Param.Ignore(category);
            Param.Ignore(symbolType);
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(parent, "parent");
            Param.Ignore(generated);

            this.category   = category;
            this.symbolType = symbolType;
        }
        private void UpdatePath(object sender, Mono.TextEditor.DocumentLocationEventArgs e)
        {
            var ast = Document.ParsedDocument as ParsedDModule;

            if (ast == null)
            {
                return;
            }

            var SyntaxTree = ast.DDom;

            if (SyntaxTree == null)
            {
                return;
            }

            // Resolve the hovered piece of code
            var        loc          = new CodeLocation(Document.Editor.Caret.Location.Column, Document.Editor.Caret.Location.Line);
            IStatement stmt         = null;
            var        currentblock = DResolver.SearchBlockAt(SyntaxTree, loc, out stmt) as IBlockNode;

            //could be an enum value, which is not IBlockNode
            if (currentblock is DEnum)
            {
                foreach (INode nd in (currentblock as DEnum).Children)
                {
                    if ((nd is DEnumValue) &&
                        ((nd.Location <= loc) && (nd.EndLocation >= loc)))
                    {
                        currentblock = nd as IBlockNode;
                        break;
                    }
                }
            }

            List <PathEntry> result = new List <PathEntry>();
            INode            node   = currentblock;

            while ((node != null) && ((node is IBlockNode) || (node is DEnumValue)))
            {
                PathEntry entry;

                var icon = DCompletionData.GetNodeIcon(node as DNode);

                entry          = new PathEntry(icon.IsNull?null: ImageService.GetPixbuf(icon.Name, IconSize.Menu), node.Name + DParameterDataProvider.GetNodeParamString(node));
                entry.Position = EntryPosition.Left;
                entry.Tag      = node;
                //do not include the module in the path bar
                if ((node.Parent != null) && !((node is DNode) && (node as DNode).IsAnonymous))
                {
                    result.Insert(0, entry);
                }
                node = node.Parent;
            }

            if (!((currentblock is DMethod) || (currentblock is DEnumValue)))
            {
                PathEntry noSelection = new PathEntry(GettextCatalog.GetString("No Selection"))
                {
                    Tag = new NoSelectionCustomNode(currentblock)
                };
                result.Add(noSelection);
            }

            var prev = CurrentPath;

            CurrentPath = result.ToArray();
            OnPathChanged(new DocumentPathChangedEventArgs(prev));
        }
Exemple #35
0
 public override void InsertIntoCode(CodeLocation location, string codeToInsert)
 {
     doc.Editor.Insert(doc.Editor.GetLine(location.Line).Offset, codeToInsert.Trim() + doc.Editor.EolMarker);
 }
Exemple #36
0
        public void GetTip(string filename, int startLine, int startIndex, int endLine, int endIndex)
        {
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _tipStart = new CodeLocation(startIndex + 1, startLine);
            _tipEnd   = new CodeLocation(startIndex + 2, startLine);
            _tipText.Clear();

            _setupEditorData();
            _editorData.CaretLocation = _tipStart;
            _editorData.SyntaxTree    = ast as DModule;
            _editorData.ModuleCode    = _sources[filename];
            // codeOffset+1 because otherwise it does not work on the first character
            _editorData.CaretOffset = getCodeOffset(_editorData.ModuleCode, _tipStart) + 1;

            ISyntaxRegion sr;

            DResolver.NodeResolutionAttempt attempt;
            var types = DResolver.ResolveTypeLoosely(_editorData, out attempt, out sr);

            _tipText.Clear();

            if (types != null)
            {
                if (sr != null)
                {
                    _tipStart = sr.Location;
                    _tipEnd   = sr.EndLocation;
                }

                DNode dn = null;

                foreach (var t in AmbiguousType.TryDissolve(types))
                {
                    _tipText.Append(NodeToolTipContentGen.Instance.GenTooltipSignature(t)).Append("\a");
                    if (t is DSymbol)
                    {
                        dn = (t as DSymbol).Definition;
                    }
                }

                while (_tipText.Length > 0 && _tipText[_tipText.Length - 1] == '\a')
                {
                    _tipText.Length--;
                }

                if (dn != null)
                {
                    VDServerCompletionDataGenerator.GenerateNodeTooltipBody(dn, _tipText);
                }

                while (_tipText.Length > 0 && _tipText[_tipText.Length - 1] == '\a')
                {
                    _tipText.Length--;
                }
            }
        }
        protected override CodeElement CreateCodeElement(string name, string fullName, CodeLocation location, CodeElement parent)
        {
            CodeField field = new CodeField(name, fullName, location, parent);

            return(field);
        }
        private object ParseProperty(StatSubtypeDefinition subtype, string propertyName, object value, CodeLocation location,
                                     string declarationName)
        {
            if (!subtype.Fields.TryGetValue(propertyName, out StatField field))
            {
                Context.LogError(DiagnosticCode.StatPropertyUnsupported, $"Property '{propertyName}' is not supported on {subtype.Name} '{declarationName}'",
                                 location?.FileName, location?.StartLine ?? 0, declarationName);
                return(null);
            }

            bool   succeeded = false;
            string errorText = null;
            object parsed;

            if (field.Type != "Passthrough")
            {
                var parser = field.GetParser(ParserFactory, Context.Definitions);
                parsed = parser.Parse((string)value, ref succeeded, ref errorText);
            }
            else
            {
                parsed    = value;
                succeeded = true;
            }

            if (errorText != null)
            {
                Context.LogError(DiagnosticCode.StatPropertyValueInvalid, $"{subtype.Name} '{declarationName}' has invalid {propertyName}: '{value}' ({errorText})",
                                 location?.FileName, location?.StartLine ?? 0, declarationName);
            }

            if (succeeded)
            {
                return(parsed);
            }
            else
            {
                return(null);
            }
        }
Exemple #39
0
 void PushNewScope(IBlockNode scope, CodeLocation caret)
 {
     new ContextFrame(this, scope, caret);
 }
        /// <summary>
        /// Calculates the indentation from the inner-most to the outer-most block/section.
        /// </summary>
        public static int CalculateBackward(IBlockNode n, CodeLocation caret)
        {
            int i    = 0;
            var line = caret.Line;

            while (n != null)
            {
                var db = n as DBlockNode;
                if (db != null)
                {
                    if (!n.BlockStartLocation.IsEmpty)
                    {
                        i += GetBlockindent(n, n.BlockStartLocation, GetLastBlockAstChild(db), caret);
                    }

                    var metaStack = db.GetMetaBlockStack(caret, true, true);
                    for (int k = metaStack.Length; k != 0; k--)
                    {
                        var mb  = metaStack[k];
                        var mbb = mb as IMetaDeclarationBlock;
                        if (mbb != null)
                        {
                            i += GetBlockindent(metaStack[i], mbb.BlockStartLocation, k == 0 ? null : metaStack[k - 1], caret);
                        }
                        else if (line > mb.Location.Line)
                        {
                            /*
                             * pragma(lib,
                             *		"kernel32.lib");
                             * private:
                             *		int a;
                             */
                            i++;
                        }
                    }
                }
                else if (n is DMethod)
                {
                    var dm = (DMethod)n;

                    /*
                     * Xvoid foo() Y{ }Z // Do not indent because 1) the method is one line large and 2) the caret is at the first line
                     *
                     * Xint foo()
                     *		@trusted
                     *		@safe nothrow // 5)
                     * in Y{ // 3) do not indent because of the brace
                     *		a + b;
                     * }Z
                     * body
                     * { | } // 4) do not indent if it's a one-lined block statement
                     * out(r) // 5) do not indent after the first definition part, if we're not inside a block
                     * {
                     *		assert(r>3456);
                     *		if(r > 10000)
                     *			a + b; } | // 6) Though we're outside the block, it's needed to indent dependent on the block's contents
                     *
                     * void foo()
                     * { } | // 7) same as 4)
                     */

                    if (line > dm.Location.Line                     // 1), 2)

                        /* No check for dm.EndLocation.Line > dm.Location.Line required due to the first check
                         * -- if the method was single-line but the line > the location line, it wasn't handled right now ;) */)
                    {
                        var s = dm.GetSubBlockAt(caret) as IStatement;

                        if (s != null)
                        {
                            if (s.EndLocation.Line > s.Location.Line &&                 // 4)
                                line > s.Location.Line)                                 // 3)
                            {
                                i += Calculate(ref s, caret);
                            }
                        }
                        else
                        {
                            // Get the block that is the most nearest to the caret
                            foreach (var b in new[] { dm.In, dm.Body, dm.Out })
                            {
                                if (b != null && caret > b.EndLocation && line == b.EndLocation.Line &&                                 // 6)
                                    (s == null || b.Location > s.EndLocation))
                                {
                                    s = b;
                                }
                            }

                            if (s != null && s.EndLocation.Line > s.Location.Line)                             // 7)
                            {
                                i += Calculate(ref s, caret);
                            }
                        }
                    }
                }

                // Handle non-IBlockNode nodes because they were not regarded during SeachBlockAt()
                // TODO: Are anonymous classes handled by SearchBlockAt()?
                if (n.Count != 0)
                {
                    foreach (var subNode in n.Children)
                    {
                        if (subNode is DVariable)
                        {
                            var dv = (DVariable)subNode;

                            /*
                             * // 1) The variable definition must take at least two lines
                             * Xint a=
                             *		1234 // 2) indent after the first line
                             *		;Z // 3) though it ends here, indent anyway.
                             *
                             * Xint a
                             *		= 1234;Z // 4)
                             */

                            if (dv.EndLocation.Line > dv.Location.Line)                        // 1)
                            {
                                if (line > dv.Location.Line &&                                 // 2)
                                    line <= dv.EndLocation.Line)                               // 3)
                                {
                                    i++;
                                }

                                var x = dv.Initializer;
                                if (x != null && line > x.Location.Line && caret < x.EndLocation)                                 // 4)
                                {
                                    i += Calculate(ref x, caret);
                                }
                            }
                        }
                    }
                }

                if (n.Parent != null)
                {
                    i++;
                    n = n.Parent as IBlockNode;
                }
            }

            return(i);
        }
 public static int CalculateForward(IBlockNode module, CodeLocation caret)
 {
     return(CalculateBackward(DResolver.SearchBlockAt(module, caret), caret));
 }
Exemple #42
0
 public static ResolutionContext Create(ParseCacheView pcl, ConditionalCompilationFlags globalConditions, IBlockNode scopedBlock, CodeLocation caret)
 {
     return(new ResolutionContext(pcl, globalConditions, scopedBlock, caret));
 }
        /// <summary>
        ///  Generate barcode and save on server
        /// </summary>
        /// <param name="name">The image name.</param>
        /// <param name="text">Barcode's text.</param>
        /// <param name="type">The barcode type.</param>
        /// <param name="format">The image format.</param>
        /// <param name="codeLocation">Property of the barcode.</param>
        /// <param name="grUnit">Measurement of barcode properties.</param>
        /// <param name="autoSize">Sets if barcode size will be updated automatically.</param>
        /// <param name="barHeight">Height of the bar.</param>
        /// <param name="imageHeight">Height of the image.</param>
        /// <param name="imageWidth">Width of the image.</param>
        /// <param name="imageQuality">Determines quality of the barcode image.</param>
        /// <param name="rotAngle">Angle of barcode orientation.</param>
        /// <param name="topMargin">Top margin.</param>
        /// <param name="bottomMargin">Bottom margin.</param>
        /// <param name="leftMargin">Left margin.</param>
        /// <param name="rightMargin">Right margin.</param>
        /// <param name="enableChecksum">Sets if checksum will be generated.</param>
        /// <param name="storage">Image's storage.</param>
        /// <param name="folder">Image's folder.</param>
        /// <param name="resolutionX">Horizontal resolution in DPI. Default is 96</param>
        /// <param name="resolutionY">Vertical resolution in DPI. Default is 96</param>
        /// <param name="dimensionX">Smallest width of barcode unit (bar or space). Default is 0.7</param>
        /// <param name="dimensionY">Smallest height of barcode unit (for 2D barcodes). Default is 2</param>
        public void GenerateBarCodeAndSaveOnServer(string name, string text, BarCodeType type,
                                                   float barHeight, float imageHeight, float imageWidth, float rotAngle,
                                                   float topMargin, float bottomMargin, float leftMargin, float rightMargin, string storage,
                                                   string folder,
                                                   BarCodeImageFormat format = BarCodeImageFormat.PNG, CodeLocation codeLocation = CodeLocation.Below, GrUnit grUnit = GrUnit.MM,
                                                   bool autoSize             = true, ImageQuality imageQuality = ImageQuality.Default, EnableChecksum enableChecksum = EnableChecksum.No,
                                                   float resolutionX         = 96, float resolutionY           = 96, double dimensionX = 0.7, float dimensionY = 2)
        {
            // PUT  barcode/{name}/generate?appSid={appSid}&text={text}&type={type}&format={format}&resolutionX={resolutionX}&resolutionY={resolutionY}&dimensionX={dimensionX}&dimensionY={dimensionY}&codeLocation={codeLocation}&grUnit={grUnit}&autoSize={autoSize}&barHeight={barHeight}&imageHeight={imageHeight}&imageWidth={imageWidth}&imageQuality={imageQuality}&rotAngle={rotAngle}&topMargin={topMargin}&bottomMargin={bottomMargin}&leftMargin={leftMargin}&rightMargin={rightMargin}&enableChecksum={enableChecksum}&storage={storage}&folder={folder}

            string apiUrl = string.Format(@"barcode/{0}/generate?text={1}&type={2}&format={3}&resolutionX={4}&resolutionY={5}&dimensionX={6}&dimensionY={7}&codeLocation={8}&grUnit={9}&autoSize={10}&barHeight={11}&imageHeight={12}&imageWidth={13}&imageQuality={14}&rotAngle={15}&topMargin={16}&bottomMargin={17}&leftMargin={18}&rightMargin={19}&enableChecksum={20}&storage={21}&folder={22}",
                                          name, text, type, format, resolutionX, resolutionY, dimensionX, dimensionY, codeLocation, grUnit, autoSize, barHeight,
                                          imageHeight, imageWidth, imageQuality, rotAngle, topMargin, bottomMargin, leftMargin, rightMargin, enableChecksum,
                                          storage, folder);

            ServiceController.Put(apiUrl, AppSid, AppKey);
        }
Exemple #44
0
        public void GetSourceLocationForMethod_ReturnsUnknownIfMethodIsAbstract()
        {
            CodeLocation codeLocation = GetSourceLocationForMethod("AbstractMethod");

            Assert.AreEqual(CodeLocation.Unknown, codeLocation);
        }
Exemple #45
0
        public ResolutionContext(ParseCacheView parseCache, ConditionalCompilationFlags gFlags, IBlockNode bn, CodeLocation caret)
        {
            this.CompilationEnvironment = gFlags;
            this.ParseCache             = parseCache;
            //Cache = new ResolutionCache<AbstractType[]>(this);
            //ValueCache = new ResolutionCache<ISymbolValue>(this);
            MixinCache = new ResolutionCache <Tuple <string, VariableValue> >(this);

            new ContextFrame(this, bn, caret);
        }
Exemple #46
0
        public void GetTip(string filename, int startLine, int startIndex, int endLine, int endIndex)
        {
            filename = normalizePath(filename);
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _tipStart = new CodeLocation(startIndex + 1, startLine);
            _tipEnd   = new CodeLocation(startIndex + 2, startLine);

            _request = Request.Tip;
            _result  = "__pending__";

            Action dg = () =>
            {
                _setupEditorData();
                _editorData.CaretLocation = _tipStart;
                _editorData.SyntaxTree    = ast as DModule;
                _editorData.ModuleCode    = _sources[filename];
                // codeOffset+1 because otherwise it does not work on the first character
                _editorData.CaretOffset = getCodeOffset(_editorData.ModuleCode, _tipStart) + 1;

                ISyntaxRegion sr = DResolver.GetScopedCodeObject(_editorData);
                LooseResolution.NodeResolutionAttempt attempt;
                AbstractType types = sr != null?LooseResolution.ResolveTypeLoosely(_editorData, sr, out attempt, true) : null;

                if (_editorData.CancelToken.IsCancellationRequested)
                {
                    return;
                }

                StringBuilder tipText = new StringBuilder();
                if (types != null)
                {
                    if (sr != null)
                    {
                        _tipStart = sr.Location;
                        _tipEnd   = sr.EndLocation;
                    }

                    DNode dn = null;

                    foreach (var t in AmbiguousType.TryDissolve(types))
                    {
                        tipText.Append(NodeToolTipContentGen.Instance.GenTooltipSignature(t)).Append("\a");
                        if (t is DSymbol)
                        {
                            dn = (t as DSymbol).Definition;
                        }
                    }

                    while (tipText.Length > 0 && tipText[tipText.Length - 1] == '\a')
                    {
                        tipText.Length--;
                    }

                    if (dn != null)
                    {
                        VDServerCompletionDataGenerator.GenerateNodeTooltipBody(dn, tipText);
                    }

                    while (tipText.Length > 0 && tipText[tipText.Length - 1] == '\a')
                    {
                        tipText.Length--;
                    }
                }
                if (_request == Request.Tip)
                {
                    _result = tipText.ToString();
                }
            };

            runAsync(dg);
        }
Exemple #47
0
 public int ToOffset(CodeLocation loc)
 {
     return(document.GetOffset(loc.Line, loc.Column));
 }
Exemple #48
0
        void UpdateOutlineSelection(object sender, Mono.TextEditor.DocumentLocationEventArgs e)
        {
            if (clickedOnOutlineItem || SyntaxTree == null || TreeStore == null)
            {
                return;
            }

            IStatement stmt;

            var caretLocation  = Document.Editor.Caret.Location;
            var caretLocationD = new CodeLocation(caretLocation.Column, caretLocation.Line);

            var currentblock = DResolver.SearchBlockAt(SyntaxTree, caretLocationD, out stmt);

            INode selectedASTNode = null;

            if (currentblock == null)
            {
                return;
            }

            foreach (var n in currentblock)
            {
                if (caretLocationD >= n.Location && caretLocationD <= n.EndLocation)
                {
                    selectedASTNode = n;
                    break;
                }
            }

            // Select parameter node if needed
            if (selectedASTNode == null && currentblock is DMethod)
            {
                foreach (var n in (currentblock as DMethod).Parameters)
                {
                    if (caretLocationD >= n.Location && caretLocationD <= n.EndLocation)
                    {
                        selectedASTNode = n;
                        break;
                    }
                }
            }

            if (selectedASTNode == null)
            {
                selectedASTNode = stmt != null ? stmt.ParentNode : currentblock;
            }

            if (selectedASTNode == null)
            {
                return;
            }

            TreeStore.Foreach((TreeModel model, TreePath path, TreeIter iter) =>
            {
                var n = model.GetValue(iter, 0);
                if (n == selectedASTNode)
                {
                    dontJumpToDeclaration = true;
                    //var parentPath = path.Copy().Up();

                    TreeView.ExpandToPath(path);
                    TreeView.Selection.SelectIter(iter);
                    dontJumpToDeclaration = false;

                    return(true);
                }

                return(false);
            });
        }
Exemple #49
0
 public ScopedObjectVisitor(CodeLocation caret)
 {
     this.caret = caret;
 }
Exemple #50
0
        void BuildTreeChildren(TreeIter ParentTreeNode, IBlockNode ParentAstNode, CodeLocation editorSelectionLocation)
        {
            if (ParentAstNode == null)
            {
                return;
            }

            if (ParentAstNode is DMethod)
            {
                if (DCompilerService.Instance.Outline.ShowFuncParams)
                {
                    var dm = ParentAstNode as DMethod;

                    if (dm.Parameters != null)
                    {
                        foreach (var p in dm.Parameters)
                        {
                            if (p.Name != "")
                            {
                                TreeIter childIter;
                                if (!ParentTreeNode.Equals(TreeIter.Zero))
                                {
                                    childIter = TreeStore.AppendValues(ParentTreeNode, p);
                                }
                                else
                                {
                                    childIter = TreeStore.AppendValues(p);
                                }

                                if (editorSelectionLocation >= p.Location &&
                                    editorSelectionLocation < p.EndLocation)
                                {
                                    TreeView.Selection.SelectIter(childIter);
                                }
                            }
                        }
                    }
                }
            }

            foreach (var n in ParentAstNode)
            {
                if (n is DEnum && (n as DEnum).IsAnonymous)
                {
                    BuildTreeChildren(ParentTreeNode, n as IBlockNode, editorSelectionLocation);
                    continue;
                }

                if (!DCompilerService.Instance.Outline.ShowFuncVariables &&
                    ParentAstNode is DMethod &&
                    n is DVariable)
                {
                    continue;
                }

                if (n is DMethod && string.IsNullOrEmpty(n.Name))                 // Check against delegates & unittests
                {
                    continue;
                }

                TreeIter childIter;
                if (!ParentTreeNode.Equals(TreeIter.Zero))
                {
                    childIter = TreeStore.AppendValues(ParentTreeNode, n);
                }
                else
                {
                    childIter = TreeStore.AppendValues(n);
                }

                if (editorSelectionLocation >= n.Location &&
                    editorSelectionLocation < n.EndLocation)
                {
                    TreeView.Selection.SelectIter(childIter);
                }

                BuildTreeChildren(childIter, n as IBlockNode, editorSelectionLocation);
            }
        }
Exemple #51
0
        void EnforceBraceStyle(BraceStyle braceStyle, CodeLocation lBrace, int rBraceLine, int rBraceColumn)
        {
            if (lBrace.IsEmpty)
            {
                return;
            }

            int lbraceOffset = document.ToOffset(lBrace);
            int rbraceOffset = document.ToOffset(rBraceLine, rBraceColumn);

            int    whitespaceStart = SearchWhitespaceStart(lbraceOffset);
            int    whitespaceEnd   = SearchWhitespaceLineStart(rbraceOffset);
            string startIndent     = "";
            string endIndent       = "";

            switch (braceStyle)
            {
            case BraceStyle.DoNotChange:
                startIndent = endIndent = null;
                break;

            case BraceStyle.EndOfLineWithoutSpace:
                startIndent = "";
                endIndent   = IsLineIsEmptyUpToEol(rbraceOffset) ? curIndent.IndentString : this.options.EolMarker + curIndent.IndentString;
                break;

            case BraceStyle.EndOfLine:
                int lastNonWs;
                var lastComments = GetCommentsBefore(lBrace, out lastNonWs);
                if (lastComments.Count != 0)
                {
                    // delete old bracket
                    AddChange(whitespaceStart, lbraceOffset - whitespaceStart + 1, "");

                    lbraceOffset = whitespaceStart = lastNonWs + 1;
                    startIndent  = " {";
                }
                else
                {
                    startIndent = " ";
                }
                endIndent = IsLineIsEmptyUpToEol(rbraceOffset) ? curIndent.IndentString : this.options.EolMarker + curIndent.IndentString;
                break;

            case BraceStyle.NextLine:
                startIndent = this.options.EolMarker + curIndent.IndentString;
                endIndent   = IsLineIsEmptyUpToEol(rbraceOffset) ? curIndent.IndentString : this.options.EolMarker + curIndent.IndentString;
                break;

            case BraceStyle.NextLineShifted2:
            case BraceStyle.NextLineShifted:
                curIndent.Push(IndentType.Block);
                startIndent = this.options.EolMarker + curIndent.IndentString;
                endIndent   = IsLineIsEmptyUpToEol(rbraceOffset) ? curIndent.IndentString : this.options.EolMarker + curIndent.IndentString;
                curIndent.Pop();
                break;
            }

            if (lbraceOffset > 0 && startIndent != null)
            {
                AddChange(whitespaceStart, lbraceOffset - whitespaceStart, startIndent);
            }
            if (rbraceOffset > 0 && endIndent != null)
            {
                AddChange(whitespaceEnd, rbraceOffset - whitespaceEnd, endIndent);
            }
        }
        protected override CodeElement CreateCodeElement(string name, string fullName, CodeLocation location, CodeElement parent)
        {
            CodeParameter parameter = new CodeParameter(name, fullName, location, parent);

            return(parameter);
        }
Exemple #53
0
 public static int CalculateRelativeIndentation(IExpression Expression, CodeLocation Caret)
 {
     return(0);
 }
        public async Task ClaimLock_Given_AlreadyLocked_Gives_FulcrumTryAgainException()
        {
            var createItem = new TestItemBare
            {
                Value = "x"
            };
            var item = await _table.CreateAndReturnAsync(createItem);

            Assert.IsNotNull(item);
            bool?lock2Success = null;

            var claimLock1Success    = new ManualResetEvent(false);
            var hasTriedToClaimLock2 = new ManualResetEvent(false);
            var thread1 = ThreadHelper.FireAndForget(async() =>
            {
                using (var scope = CreateStandardScope())
                {
                    var lockedItem = await _table.SearchSingleAndLockWhereAsync("Id=@Id", new { Id = item.Id });
                    FulcrumAssert.IsNotNull(lockedItem);
                    claimLock1Success.Set();
                    FulcrumAssert.IsTrue(hasTriedToClaimLock2.WaitOne(TimeSpan.FromSeconds(1)), CodeLocation.AsString());
                    scope.Complete();
                }
            });
            var thread2 = ThreadHelper.FireAndForget(async() =>
            {
                FulcrumAssert.IsTrue(claimLock1Success.WaitOne(TimeSpan.FromSeconds(1)));
                using (var scope = CreateStandardScope())
                {
                    try
                    {
                        var lockedItem = await _table.SearchSingleAndLockWhereAsync("Id=@Id", new { Id = item.Id });
                        FulcrumAssert.IsNotNull(lockedItem);
                        lock2Success = true;
                        scope.Complete();
                    }
                    catch (FulcrumTryAgainException)
                    {
                        lock2Success = false;
                    }
                }
                hasTriedToClaimLock2.Set();
            });

            Assert.IsTrue(thread2.Join(TimeSpan.FromSeconds(5)));
            Assert.IsNotNull(lock2Success);
            Assert.IsFalse(lock2Success);
            Assert.IsTrue(thread1.Join(TimeSpan.FromSeconds(1)));
        }
        static int Calculate(ref IStatement s, CodeLocation caret)
        {
            int i = 0;

            return(i);
        }
Exemple #56
0
        public void GetDefinition(string filename, int startLine, int startIndex, int endLine, int endIndex)
        {
            filename = normalizePath(filename);
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _tipStart = new CodeLocation(startIndex + 1, startLine);
            _tipEnd   = new CodeLocation(endIndex + 1, endLine);

            _request = Request.Definition;
            _result  = "__pending__";

            Action dg = () =>
            {
                _setupEditorData();
                _editorData.CaretLocation = _tipEnd;
                _editorData.SyntaxTree    = ast as DModule;
                _editorData.ModuleCode    = _sources[filename];
                // codeOffset+1 because otherwise it does not work on the first character
                _editorData.CaretOffset = getCodeOffset(_editorData.ModuleCode, _tipStart) + 2;

                ISyntaxRegion sr = DResolver.GetScopedCodeObject(_editorData);
                LooseResolution.NodeResolutionAttempt attempt;
                var rr = sr != null?LooseResolution.ResolveTypeLoosely(_editorData, sr, out attempt, true) : null;

                StringBuilder tipText = new StringBuilder();
                if (rr != null)
                {
                    DNode n = null;
                    foreach (var t in AmbiguousType.TryDissolve(rr))
                    {
                        n = DResolver.GetResultMember(t, true);
                        if (n != null)
                        {
                            break;
                        }
                    }

                    if (n != null)
                    {
                        if (tipText.Length > 0)
                        {
                            tipText.Append("\n");
                        }
                        bool decl = false;
                        var  mthd = n as DMethod;
                        if (mthd != null)
                        {
                            decl = mthd.Body == null;
                        }
                        else if (n.ContainsAttribute(DTokens.Extern))
                        {
                            decl = true;
                        }
                        if (decl)
                        {
                            tipText.Append("EXTERN:");
                        }

                        _tipStart = n.Location;
                        _tipEnd   = n.EndLocation;
                        INode node = n.NodeRoot;
                        if (node is DModule)
                        {
                            tipText.Append((node as DModule).FileName);
                        }
                    }
                }
                if (!_editorData.CancelToken.IsCancellationRequested && _request == Request.Definition)
                {
                    _result = tipText.ToString();
                }
            };

            runAsync(dg);
        }
        static int Calculate(ref IExpression x, CodeLocation caret)
        {
            int i = 0;

            return(i);
        }
Exemple #58
0
        /// <summary>
        /// Checks the positioning of method parameters which are split across multiple lines.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <param name="arguments">
        /// The method arguments.
        /// </param>
        /// <param name="openingBracketNode">
        /// The opening bracket token.
        /// </param>
        /// <param name="friendlyTypeText">
        /// The friendly type text to use in reporting violations.
        /// </param>
        private void CheckSplitMethodArgumentList(CsElement element, IArgumentList arguments, Node <CsToken> openingBracketNode, string friendlyTypeText)
        {
            Param.AssertNotNull(element, "element");
            Param.AssertNotNull(arguments, "arguments");
            Param.AssertNotNull(openingBracketNode, "openingBracketNode");

            Node <CsToken> previousComma = null;
            bool           commaOnSameLineAsPreviousParameterViolation = false;

            for (int i = 0; i < arguments.Count; ++i)
            {
                CodeLocation location          = arguments.Location(i);
                int          argumentStartLine = location.LineNumber;

                CsTokenList tokens = arguments.Tokens(i);

                // Some types of parameters or arguments are not allowed to span across multiple lines.
                if (location.LineSpan > 1 && !arguments.MaySpanMultipleLines(i))
                {
                    this.AddViolation(element, argumentStartLine, Rules.ParameterMustNotSpanMultipleLines);
                }

                if (i == 0)
                {
                    // The first argument must start on the line after the opening bracket
                    if (argumentStartLine != openingBracketNode.Value.LineNumber + 1)
                    {
                        int commentLineSpan = MeasureCommentLinesAfter(openingBracketNode);

                        if (argumentStartLine != openingBracketNode.Value.LineNumber + commentLineSpan + 1)
                        {
                            this.AddViolation(element, argumentStartLine, Rules.SplitParametersMustStartOnLineAfterDeclaration, friendlyTypeText);
                        }
                    }
                }
                else
                {
                    // The parameter must begin on the line after the previous comma.
                    Debug.Assert(previousComma != null, "The previous comma should have been set.");
                    if (!commaOnSameLineAsPreviousParameterViolation)
                    {
                        if (argumentStartLine != previousComma.Value.LineNumber + 1)
                        {
                            int commentLineSpan = MeasureCommentLinesAfter(previousComma);

                            if (argumentStartLine != previousComma.Value.LineNumber + commentLineSpan + 1)
                            {
                                this.AddViolation(element, argumentStartLine, Rules.ParameterMustFollowComma);
                            }
                        }
                    }
                }

                commaOnSameLineAsPreviousParameterViolation = false;

                // Find the comma after the token list.
                if (i < arguments.Count - 1)
                {
                    for (Node <CsToken> tokenNode = tokens.Last.Next; tokenNode != null; tokenNode = tokenNode.Next)
                    {
                        if (tokenNode.Value.CsTokenType == CsTokenType.Comma)
                        {
                            previousComma = tokenNode;

                            // The comma must be on the same line as the previous parameter.
                            if (previousComma.Value.LineNumber != location.EndPoint.LineNumber)
                            {
                                int commentLineSpan = MeasureCommentLinesBetween(tokens.Last, previousComma, false);

                                if (previousComma.Value.LineNumber != location.EndPoint.LineNumber + commentLineSpan)
                                {
                                    this.AddViolation(element, tokenNode.Value.LineNumber, Rules.CommaMustBeOnSameLineAsPreviousParameter);
                                    commaOnSameLineAsPreviousParameterViolation = true;
                                }
                            }

                            break;
                        }
                    }
                }
            }
        }
Exemple #59
0
 public void SetLocation(CodeLocation location)
 {
     _current = location;
 }
Exemple #60
0
        /// <summary>
        /// Binary search implementation for ordered syntax region (derivative) lists.
        /// </summary>
        public static SR SearchRegionAt <SR>(Func <int, SR> childGetter, int childCount, CodeLocation Where) where SR : ISyntaxRegion
        {
            int start      = 0;
            SR  midElement = default(SR);
            int midIndex   = 0;
            int len        = childCount;

            while (len > 0)
            {
                midIndex = (len % 2 + len) / 2;

                // Take an element from the middle
                if ((midElement = childGetter(start + midIndex - 1)) == null)
                {
                    break;
                }

                // If 'Where' is beyond its start location
                if (Where >= midElement.Location)
                {
                    start += midIndex;

                    // If we've reached the (temporary) goal, break immediately
                    if (Where <= midElement.EndLocation)
                    {
                        break;
                    }
                    // If it's the last tested element and if the caret is beyond the end location,
                    // return the Parent instead the last tested child
                    else if (midIndex == len)
                    {
                        midElement = default(SR);
                        break;
                    }
                }
                else if (midIndex == len)
                {
                    midElement = default(SR);
                    break;
                }

                len -= midIndex;
            }

            return(midElement);
        }