public void WhenUnitNotRegistered_Throws() { var currencyDefinition = new SymbolDefinition(); currencyDefinition.AddDefinition("glob", "I"); Assert.Throws <ArgumentException>( () => { var a = currencyDefinition["prok"]; }); }
public static IEnumerable<string> GetShortcuts(SymbolDefinition context, FGGrammar.TokenSet expected) { foreach (var snippet in snippets) { var text = snippet.Value; if (IsValid(ref text, context, expected)) yield return snippet.Key; } }
public static void FindAllReferences(SymbolDefinition symbol, string localAssetPath) { if (symbol.kind == SymbolKind.Accessor || symbol.kind == SymbolKind.Constructor || symbol.kind == SymbolKind.Destructor) { symbol = symbol.parentSymbol; } if (symbol == null) { return; } symbol = symbol.GetGenericSymbol(); var candidates = FindReferenceCandidates(symbol, localAssetPath); var searchOptions = new FindResultsWindow.SearchOptions { text = symbol.name, matchWord = true, matchCase = true, }; var candidateGuids = new string[candidates.Count]; for (int i = 0; i < candidates.Count; i++) { candidateGuids[i] = AssetDatabase.AssetPathToGUID(candidates[i]); } var searchForVarRefs = symbol is TypeDefinitionBase && symbol.kind != SymbolKind.Delegate; if (searchForVarRefs) { searchOptions.altText1 = "var"; var builtInTypesEnumerator = SymbolDefinition.builtInTypes.GetEnumerator(); for (var i = 0; i < 16; i++) { builtInTypesEnumerator.MoveNext(); var type = builtInTypesEnumerator.Current.Value; if (type == symbol) { searchOptions.altText2 = builtInTypesEnumerator.Current.Key; break; } } } var resultsWindow = FindResultsWindow.Create( "References to " + symbol.FullName, FindAllInSingleFile, candidateGuids, searchOptions, "References"); resultsWindow.SetFilesValidator(ValidateFileForReferences); resultsWindow.SetResultsValidator(ValidateResultAsReference, symbol); }
int CalcSize(SymbolDefinition symbol) // repeat until all set... { foreach (var child in symbol.Children) { child.Size = SetSize(child); } var size = TotalOfChildSizes(symbol); return(size); }
public static StorageArea CreateReceivingStorageArea(SymbolDefinition symbol) { if (symbol == null) { return(null); } var storage = new DataOrConditionStorageArea(new SymbolReference(symbol)); return(storage); }
public static Texture2D GetSymbolIcon(SymbolDefinition symbol) { if (symbolIcons == null) { LoadSymbolIcons(); } return(symbolIcons[ (int)symbol.kind, symbol.IsPublic | symbol.IsInternal ? 0 : symbol.IsProtected ? 1 : 2] ?? keywordIcon); }
int SetSize(SymbolDefinition symbol) { if (symbol.Size == -1) { var names = symbol.Tokens.Select(tok => tok.lexeme); var name = string.Join('.', names); var type = symbol.LookUpType(name); return(type.Size); } return(-1); }
public static string NameOf(SymbolDefinition symbol) { var name = symbol.name; if (shortAttributeNames && symbol.kind == SymbolKind.Class && symbol.name.EndsWith("Attribute") && symbol.name != "Attribute") { name = name.Substring(0, name.Length - "Attribute".Length); } return(name); }
public override TypeDefinitionBase SubstituteTypeParameters(SymbolDefinition context) { var constructedElement = elementType.SubstituteTypeParameters(context); if (constructedElement != elementType) { return(constructedElement.MakeArrayType(rank)); } return(base.SubstituteTypeParameters(context)); }
public SymbolDefinition(string typeName, string instanceName, SymbolDefinition parent, int size, AccessModifier accessModifier, bool isFunctional, Token[] tokens) { TypeName = typeName; InstanceName = instanceName; Parent = parent; Children = new List <SymbolDefinition>(); Modifier = accessModifier; IsFunctional = isFunctional; Tokens = tokens; Size = size; }
public SymbolDefinition LookUpTypeHere(string typeName) { SymbolDefinition currentType = this; var typeNameParts = typeName.Split('.'); foreach (var typeNamePart in typeNameParts) { currentType = currentType.Children.Find(curr => curr.TypeName == typeNamePart); } return(currentType); }
public static string Get(string shortcut, SymbolDefinition context, FGGrammar.TokenSet expected) { string text; if (!snippets.TryGetValue(shortcut, out text)) return null; if (!IsValid(ref text, context, expected)) return null; return text; }
public override SymbolDefinition AddDeclaration(SymbolDeclaration symbol) { if (symbol.kind == SymbolKind.Parameter) { SymbolDefinition definition = AddParameter(symbol); symbol.definition = definition; return(definition); } return(base.AddDeclaration(symbol)); }
private static SymbolDefinition InitializeDefinitions() { var definitions = new SymbolDefinition(); definitions.AddDefinition("glob", "I"); definitions.AddDefinition("prok", "V"); definitions.AddDefinition("pish", "X"); definitions.AddDefinition("tegj", "L"); return(definitions); }
public static IEnumerable <string> GetShortcuts(SymbolDefinition context, FGGrammar.TokenSet expected) { foreach (var snippet in snippets) { var text = snippet.Value; if (IsValid(ref text, context, expected)) { yield return(snippet.Key); } } }
public SymbolDefinition GetThisInstance() { if (thisReferenceCache == null) { if (IsStatic) { return(thisReferenceCache = unknownType); } thisReferenceCache = new SD_Instance_This(new SymbolReference(this)); } return(thisReferenceCache); }
public IEnumerable<SnippetCompletion> EnumSnippets( SymbolDefinition context, FGGrammar.TokenSet expectedTokens, SyntaxToken tokenLeft, Scope scope) { if (scope == null) yield break; var bodyScope = scope as BodyScope ?? scope.parentScope as BodyScope; if (bodyScope == null) yield break; var contextType = bodyScope.definition as TypeDefinitionBase; if (contextType == null || contextType.kind != SymbolKind.Class && contextType.kind != SymbolKind.Struct) yield break; context = contextType; if (tokenLeft == null || tokenLeft.parent == null || tokenLeft.parent.parent == null) yield break; if (tokenLeft.tokenKind != SyntaxToken.Kind.Punctuator) yield break; if (tokenLeft.text != "{" && tokenLeft.text != "}" && tokenLeft.text != ";") yield break; for (var i = contextType.members.Count; i --> 0; ) { var member = contextType.members[i]; if (member.kind == SymbolKind.Field) { var type = member.TypeOf(); if (type == null || type.kind == SymbolKind.Error || !(type is TypeDefinitionBase)) continue; var fieldName = member.name; if (string.IsNullOrEmpty(fieldName) || fieldName[0] == '.') continue; fieldName = char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1); var propertyName = fieldName; for (var suffix = 1; contextType.members.Contains(propertyName, -1); ++suffix) propertyName = fieldName + suffix.ToString(); yield return new MyCompletion(propertyName, member, true);// "{0} {{ get {{...}} set {{...}} }}"); yield return new MyCompletion(propertyName, member, false);// "{0} {{ get {{...}} }}"); } } }
public override void ResolveAttribute(SyntaxTreeNode_Leaf leaf) { leaf.ResolvedSymbol = null; var id = SymbolDefinition.DecodeId(leaf.token.text); for (int i = declaration.typeAliases.Count; i-- > 0;) { if (declaration.typeAliases[i].name == id) { if (declaration.typeAliases[i].type != null) { leaf.ResolvedSymbol = declaration.typeAliases[i].type.Definition; return; } else { break; } } } var parentScopeDef = parentScope != null ? ((Scope_Namespace)parentScope).definition : null; for (var nsDef = definition; leaf.ResolvedSymbol == null && nsDef != null && nsDef != parentScopeDef; nsDef = nsDef.parentSymbol as SD_NameSpace) { nsDef.ResolveAttributeMember(leaf, this); } if (leaf.ResolvedSymbol == null) { foreach (var nsRef in declaration.importedNamespaces) { if (nsRef.IsBefore(leaf) && nsRef.Definition != null) { nsRef.Definition.ResolveAttributeMember(leaf, this); if (leaf.ResolvedSymbol != null) { break; } } } } if (leaf.ResolvedSymbol == null && parentScope != null) { parentScope.ResolveAttribute(leaf); } }
public override SymbolDefinition AddDeclaration(SymbolDeclaration symbol) { symbol.scope = this; if (localSymbols == null) { localSymbols = new List <SymbolDefinition>(); } var definition = SymbolDefinition.Create(symbol); localSymbols.Add(definition); return(definition); }
void CalcChildOffsets(SymbolDefinition symbol) { int offset = 0; foreach (var child in symbol.Children) { if (child.IsMember) { child.Offset = offset; offset += child.Size; CalcChildOffsets(child); } } }
public override SymbolDefinition AddDeclaration(SymbolDeclaration symbol) { if (symbol.kind == SymbolKind.Parameter) { SymbolDefinition definition = AddParameter(symbol); // if (!members.TryGetValue(symbolName, out definition) || definition is ReflectedMember || definition is ReflectedType) // definition = AddMember(symbol); symbol.definition = definition; return(definition); } return(base.AddDeclaration(symbol)); }
public static void WriteToSng(Sng2014File sng, string glyphDefinitionsPath) { GlyphDefinitions glyphDefs; using (var reader = new StreamReader(glyphDefinitionsPath)) { glyphDefs = new XmlStreamingDeserializer <GlyphDefinitions>(reader).Deserialize(); } sng.SymbolsTexture.SymbolsTextures[0].Width = glyphDefs.TextureWidth; sng.SymbolsTexture.SymbolsTextures[0].Height = glyphDefs.TextureHeight; var symbolDefs = new List <SymbolDefinition>(glyphDefs.Glyphs.Count); foreach (var glyph in glyphDefs.Glyphs) { if (Encoding.UTF8.GetByteCount(glyph.Symbol) > 12) { throw new Exception(String.Format("The following symbol does not fit into 12 bytes when encoded in UTF-8: {0}", glyph.Symbol)); } var sDef = new SymbolDefinition { Rect_Inner = new Rect { xMax = glyph.InnerXMax, xMin = glyph.InnerXMin, yMax = glyph.InnerYMax, yMin = glyph.InnerYMin }, Rect_Outter = new Rect { xMax = glyph.OuterXMax, xMin = glyph.OuterXMin, yMax = glyph.OuterYMax, yMin = glyph.OuterYMin } }; Encoding.UTF8.GetBytes(glyph.Symbol).CopyTo(sDef.Text, 0); symbolDefs.Add(sDef); } sng.SymbolsDefinition = new SymbolDefinitionSection { Count = symbolDefs.Count, SymbolDefinitions = symbolDefs.ToArray() }; }
bool CheckAllSizesSet(SymbolDefinition symbol) { if (!ChildSizesSet(symbol) || symbol.TypeName != "" && symbol.Size == -1) { return(false); } foreach (var child in symbol.Children) { if (child.Children.Count > 0) { return(CheckAllSizesSet(child)); } } return(true); }
public static List<SymbolDeclaration> FindDeclarations(SymbolDefinition symbol) { var candidates = FindDefinitionCandidates(symbol); foreach (var c in candidates) { var asset = AssetDatabase.LoadAssetAtPath(c, typeof(TextAsset)) as TextAsset; if (!asset) continue; var buffer = FGTextBufferManager.GetBuffer(asset); buffer.LoadImmediately(); } var newSymbol = symbol.Rebind(); var declarations = newSymbol == null ? null : newSymbol.declarations; return declarations ?? symbol.declarations; }
public static string Get(string shortcut, SymbolDefinition context, FGGrammar.TokenSet expected) { string text; if (!snippets.TryGetValue(shortcut, out text)) { return(null); } if (!IsValid(ref text, context, expected)) { return(null); } return(text); }
public override SymbolDefinition FindName(string symbolName, int numTypeParameters) { symbolName = SymbolDefinition.DecodeId(symbolName); if (numTypeParameters == 0 && localSymbols != null) { for (var i = localSymbols.Count; i-- > 0;) { if (localSymbols[i].name == symbolName) { return(localSymbols[i]); } } } return(null); }
public SD_Mehod_ReflectedConstructor(ConstructorInfo constructorInfo, SymbolDefinition memberOf) { modifiers = constructorInfo.IsPublic ? Modifiers.Public : constructorInfo.IsFamilyOrAssembly ? Modifiers.Internal | Modifiers.Protected : constructorInfo.IsAssembly ? Modifiers.Internal : constructorInfo.IsFamily ? Modifiers.Protected : Modifiers.Private; if (constructorInfo.IsAbstract) { modifiers |= Modifiers.Abstract; } if (constructorInfo.IsStatic) { modifiers |= Modifiers.Static; } accessLevel = AccessLevelFromModifiers(modifiers); name = ".ctor"; kind = SymbolKind.Constructor; parentSymbol = memberOf; returnType = new SymbolReference(memberOf); if (parameters == null) { parameters = new List <SD_Instance_Parameter>(); } foreach (var p in constructorInfo.GetParameters()) { var isByRef = p.ParameterType.IsByRef; var parameterType = isByRef ? p.ParameterType.GetElementType() : p.ParameterType; var parameterToAdd = new SD_Instance_Parameter { kind = SymbolKind.Parameter, parentSymbol = this, name = p.Name, type = ReflectedTypeReference.ForType(parameterType), modifiers = isByRef ? (p.IsOut ? Modifiers.Out : Modifiers.Ref) : Attribute.IsDefined(p, typeof(ParamArrayAttribute)) ? Modifiers.Params : Modifiers.None, }; if (p.RawDefaultValue != DBNull.Value) { parameterToAdd.defaultValue = p.RawDefaultValue == null ? "null" : p.RawDefaultValue.ToString(); } parameters.Add(parameterToAdd); } }
public override void Resolve(SyntaxTreeNode_Leaf leaf, int numTypeArgs, bool asTypeOnly) { leaf.ResolvedSymbol = null; if (numTypeArgs == 0 && !asTypeOnly) { SyntaxTreeNode_Base target = null; if (leaf.m_iChildIndex == 0 && leaf.Parent != null && leaf.Parent.Parent == parseTreeNode) { var node = parseTreeNode .Parent .Parent .Parent; if (node.RuleName == "objectCreationExpression") { target = node.Parent.NodeAt(1); } else { target = node.LeafAt(0); } if (target != null) { var targetSymbol = target.ResolvedSymbol; if (targetSymbol != null) { targetSymbol = targetSymbol.TypeOf(); } else { targetSymbol = SymbolDefinition.ResolveNode(target, parentScope); } if (targetSymbol != null) { targetSymbol.ResolveMember(leaf, parentScope, 0, false); } return; } } } base.Resolve(leaf, numTypeArgs, asTypeOnly); }
public override TypeDefinitionBase SubstituteTypeParameters(SymbolDefinition context) { var target = this; var parentType = parentSymbol as TypeDefinitionBase; if (parentType != null) { parentType = parentType.SubstituteTypeParameters(context); var constructedParent = parentType as SD_Type_Constructed; if (constructedParent != null) { target = constructedParent.GetConstructedMember(this.genericTypeDefinition) as SD_Type_Constructed; } } if (typeArguments == null) { return(target); } var constructNew = false; var newArguments = new SymbolReference[typeArguments.Length]; for (var i = 0; i < newArguments.Length; ++i) { newArguments[i] = typeArguments[i]; var original = typeArguments[i] != null ? typeArguments[i].Definition as TypeDefinitionBase : null; if (original == null) { continue; } var substitute = original.SubstituteTypeParameters(target); substitute = substitute.SubstituteTypeParameters(context); if (substitute != original) { newArguments[i] = new SymbolReference(substitute); constructNew = true; } } if (!constructNew) { return(target); } return(ConstructType(newArguments)); }
void CalcSizes(SymbolDefinition symbol) // repeat until all set... { foreach (var child in symbol.Children) { if (child.Size == -1) { if (child.Children.Count > 0) { var total = CalcSize(child); child.Size = total; } else { SetSize(child); } } } }
public override void GetCompletionData(Dictionary <string, SymbolDefinition> data, bool fromInstance, SD_Assembly assembly) { var baseNode = completionNode; if (baseNode.Parent != null && (baseNode.Parent == parseTreeNode || baseNode.m_iChildIndex == 0 && baseNode.Parent.Parent == parseTreeNode)) { SymbolDefinition target = null; SyntaxTreeNode_Base targetNode = null; var node = parseTreeNode .Parent .Parent .Parent; if (node.RuleName == "objectCreationExpression") { targetNode = node.Parent; target = SymbolDefinition.ResolveNode(targetNode); var targetAsType = target as TypeDefinitionBase; if (targetAsType != null) { target = targetAsType.GetThisInstance(); } } else { targetNode = node.Parent.LeafAt(0); target = SymbolDefinition.ResolveNode(node.Parent.LeafAt(0)); } if (target != null) { HashSet <SymbolDefinition> completions = new HashSet <SymbolDefinition>(); SymbolResolver.GetCompletions(IdentifierCompletionsType.Member, targetNode, completions, completionAssetPath); foreach (var symbol in completions) { data.Add(symbol.name, symbol); } } } else { base.GetCompletionData(data, fromInstance, assembly); } }
private SymbolDefinition ConstructMember(SymbolDefinition member) { SymbolDefinition symbol; if (member is SD_Instance) { symbol = new SD_Instance_Constructed(member as SD_Instance); } if (member is SD_Type) { symbol = (member as SD_Type).ConstructType(null);// new ConstructedTypeDefinition(member as TypeDefinition, null); } else { symbol = new SD_ConstructedReference(member); } symbol.parentSymbol = this; return(symbol); }
public override void Resolve(SyntaxTreeNode_Leaf leaf, int numTypeArgs, bool asTypeOnly) { leaf.ResolvedSymbol = null; if (!asTypeOnly && localSymbols != null) { var id = SymbolDefinition.DecodeId(leaf.token.text); for (var i = localSymbols.Count; i-- > 0;) { if (localSymbols[i].name == id) { leaf.ResolvedSymbol = localSymbols[i]; return; } } } base.Resolve(leaf, numTypeArgs, asTypeOnly); }
public static List <SymbolDeclaration> FindDeclarations(SymbolDefinition symbol) { var candidates = FindDefinitionCandidates(symbol); foreach (var c in candidates) { var asset = AssetDatabase.LoadAssetAtPath(c, typeof(TextAsset)) as TextAsset; if (!asset) { continue; } var buffer = FGTextBufferManager.GetBuffer(asset); buffer.LoadImmediately(); } var newSymbol = FindNewSymbol(symbol); return(newSymbol == null ? null : newSymbol.declarations); }
static List<string> FindDefinitionCandidates(SymbolDefinition symbol) { var result = new List<string>(); if (assets != null) assets.Clear(); var symbolType = symbol; if (symbol.kind == SymbolKind.Namespace) return result; while (symbolType != null && symbolType.kind != SymbolKind.Class && symbolType.kind != SymbolKind.Struct && symbolType.kind != SymbolKind.Enum && symbolType.kind != SymbolKind.Interface && symbolType.kind != SymbolKind.Delegate) { symbolType = symbolType.parentSymbol; } var assembly = symbolType.Assembly; var assemblyId = assembly.assemblyId; FindAllAssemblyScripts(assemblyId); for (int i = assets.Count; i --> 0; ) assets[i] = AssetDatabase.GUIDToAssetPath(assets[i]); string[] words; string typeName = symbolType.name; switch (symbolType.kind) { case SymbolKind.Class: words = new [] { "class", typeName }; break; case SymbolKind.Struct: words = new [] { "struct", typeName }; break; case SymbolKind.Interface: words = new [] { "interface", typeName }; break; case SymbolKind.Enum: words = new [] { "enum", typeName }; break; case SymbolKind.Delegate: words = new [] { typeName, "(" }; break; default: return result; } for (int i = assets.Count; i --> 0; ) if (ContainsWordsSequence(assets[i], words)) result.Add(assets[i]); return result; }
public MyCompletion(string propertyName, SymbolDefinition field, bool withSetter) : base(propertyName, withSetter ? "{0} {{ get {{...}} set {{...}} }}" : "{0} {{ get {{...}} }}") { this.field = field; this.withSetter = withSetter; }
public void SetResultsValidator(ResultTypeValidator validateResultFunction, SymbolDefinition referencedSymbol) { this.validateResultFunction = validateResultFunction; this.referencedSymbol = referencedSymbol; title = "References"; Repaint(); }
private void OnRequestBrowse(SymbolDefinition.SymbolField sender) { string expr = _edSvc.EditExpression(sender.Content, _cls, _providerName, _featureSourceId, true); if (expr != null) sender.Content = expr; }
public string Get( string shortcut, SymbolDefinition context, FGGrammar.TokenSet expectedTokens, Scope scope) { return null; }
private static string GetTooltipText(SymbolDefinition symbol, ParseTree.Leaf leaf) { if (symbol.kind == SymbolKind.Method) { var method = symbol as MethodDefinition; if (method != null && method.IsExtensionMethod) { var nodeLeft = leaf.parent; if (nodeLeft != null && nodeLeft.RuleName == "accessIdentifier") { nodeLeft = nodeLeft.FindPreviousNode() as ParseTree.Node; if (nodeLeft != null && (nodeLeft.RuleName == "primaryExpressionPart" || nodeLeft.RuleName == "primaryExpressionStart")) { var symbolLeft = FGResolver.GetResolvedSymbol(nodeLeft); if (symbolLeft != null && symbolLeft.kind != SymbolKind.Error && !(symbolLeft is TypeDefinitionBase)) return symbol.GetTooltipTextAsExtensionMethod(); } } } } return symbol.GetTooltipText(); }
static FindResultsWindow.ResultType ValidateResultAsReference(string assetGuid, TextPosition location, int length, ref SymbolDefinition referencedSymbol) { var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid); if (string.IsNullOrEmpty(assetPath)) return FindResultsWindow.ResultType.RemoveResult; var isCsScript = assetPath.EndsWith(".cs", System.StringComparison.OrdinalIgnoreCase); var buffer = FGTextBufferManager.GetBuffer(assetGuid); if (buffer == null) return FindResultsWindow.ResultType.RemoveResult; if (buffer.Parser == null) { buffer.LoadImmediately(); referencedSymbol = referencedSymbol.Rebind(); } var formatedLine = buffer.formatedLines[location.line]; var textLine = buffer.lines[location.line]; var isVarResult = length == 3 && (referencedSymbol is TypeDefinitionBase) && textLine.Substring(location.index, length) == "var"; if (isCsScript) { if (formatedLine.regionTree.kind > FGTextBuffer.RegionTree.Kind.LastActive) { if (isVarResult) return FindResultsWindow.ResultType.RemoveResult; return FindResultsWindow.ResultType.InactiveCode; } } else if (isVarResult) { return FindResultsWindow.ResultType.RemoveResult; } int tokenIndex; bool atTokenEnd; var token = buffer.GetTokenAt(new TextPosition(location.line, location.index + 1), out location.line, out tokenIndex, out atTokenEnd); switch (token.tokenKind) { case SyntaxToken.Kind.Preprocessor: return FindResultsWindow.ResultType.RemoveResult; case SyntaxToken.Kind.Comment: case SyntaxToken.Kind.PreprocessorArguments: case SyntaxToken.Kind.PreprocessorSymbol: if (isVarResult) return FindResultsWindow.ResultType.RemoveResult; return FindResultsWindow.ResultType.Comment; case SyntaxToken.Kind.StringLiteral: case SyntaxToken.Kind.VerbatimStringLiteral: if (isVarResult) return FindResultsWindow.ResultType.RemoveResult; return FindResultsWindow.ResultType.String; } if (!isCsScript || token.parent == null) return FindResultsWindow.ResultType.UnresolvedSymbol; var resolvedSymbol = token.parent.resolvedSymbol; if (resolvedSymbol == null || resolvedSymbol.kind == SymbolKind.Error) FGResolver.ResolveNode(token.parent.parent); if (resolvedSymbol != null && resolvedSymbol.kind == SymbolKind.MethodGroup && token.parent.parent != null) { var nextLeaf = token.parent.parent.FindNextLeaf(); if (nextLeaf != null && nextLeaf.IsLit("(")) { var nextNode = nextLeaf.parent; if (nextNode.RuleName == "arguments") { FGResolver.ResolveNode(nextNode); if (token.parent != null) if (token.parent.resolvedSymbol == null || token.parent.resolvedSymbol.kind == SymbolKind.Error) token.parent.resolvedSymbol = resolvedSymbol; } } } resolvedSymbol = token.parent != null ? token.parent.resolvedSymbol : null; if (resolvedSymbol == null || resolvedSymbol.kind == SymbolKind.Error) return FindResultsWindow.ResultType.UnresolvedSymbol; if (resolvedSymbol.kind == SymbolKind.Constructor || resolvedSymbol.kind == SymbolKind.Destructor) resolvedSymbol = resolvedSymbol.parentSymbol; if (resolvedSymbol == null || resolvedSymbol.kind == SymbolKind.Error) return FindResultsWindow.ResultType.UnresolvedSymbol; var constructedSymbol = resolvedSymbol; resolvedSymbol = resolvedSymbol.GetGenericSymbol(); if (referencedSymbol.kind == SymbolKind.MethodGroup && resolvedSymbol.kind == SymbolKind.Method) resolvedSymbol = resolvedSymbol.parentSymbol; if (resolvedSymbol != referencedSymbol) { var typeArgument = referencedSymbol as TypeDefinitionBase; var constructedType = constructedSymbol as ConstructedTypeDefinition; if (isVarResult && typeArgument != null && constructedType != null) if (IsUsedAsTypeArgument(typeArgument.GetGenericSymbol() as TypeDefinitionBase, constructedType)) return FindResultsWindow.ResultType.VarTemplateReference; if (resolvedSymbol.kind == SymbolKind.Method && referencedSymbol.kind == SymbolKind.Method) { if (resolvedSymbol.parentSymbol == referencedSymbol.parentSymbol) return FindResultsWindow.ResultType.MethodOverload; var resolvedMethod = resolvedSymbol as MethodDefinition; var referencedMethod = referencedSymbol as MethodDefinition; if (resolvedMethod != null && referencedMethod != null) { var resolvedType = resolvedMethod.parentSymbol as TypeDefinitionBase ?? resolvedMethod.parentSymbol.parentSymbol as TypeDefinitionBase; var referencedType = referencedMethod.parentSymbol as TypeDefinitionBase ?? referencedMethod.parentSymbol.parentSymbol as TypeDefinitionBase; var isInterface = resolvedType.kind == SymbolKind.Interface || referencedType.kind == SymbolKind.Interface; var resolvedIsVirtual = isInterface || resolvedMethod.IsOverride || resolvedMethod.IsVirtual || resolvedMethod.IsAbstract; var referencedIsVirtual = isInterface || referencedMethod.IsOverride || referencedMethod.IsVirtual || referencedMethod.IsAbstract; if (resolvedIsVirtual && referencedIsVirtual) { if (System.Linq.Enumerable.SequenceEqual( System.Linq.Enumerable.Select(resolvedMethod.GetParameters(), x => x.TypeOf()), System.Linq.Enumerable.Select(referencedMethod.GetParameters(), x => x.TypeOf()) )) { if (resolvedType.DerivesFrom(referencedType)) return FindResultsWindow.ResultType.OverridingMethod; if (referencedType.DerivesFrom(resolvedType)) return FindResultsWindow.ResultType.OverriddenMethod; } } } } if (resolvedSymbol.kind != SymbolKind.MethodGroup || referencedSymbol.parentSymbol != resolvedSymbol) return FindResultsWindow.ResultType.RemoveResult; } if (isVarResult) return FindResultsWindow.ResultType.VarReference; if (FGResolver.IsWriteReference(token)) return FindResultsWindow.ResultType.WriteReference; return FindResultsWindow.ResultType.ReadReference; }
static List<string> FindReferenceCandidates(SymbolDefinition symbol, string localAssetPath) { var result = new List<string> { localAssetPath }; if (assets != null) assets.Clear(); else assets = new List<string>(); if (symbol.kind == SymbolKind.CatchParameter || symbol.kind == SymbolKind.Destructor || symbol.kind == SymbolKind.ForEachVariable || symbol.kind == SymbolKind.FromClauseVariable || symbol.kind == SymbolKind.Label || symbol.kind == SymbolKind.LambdaExpression || symbol.kind == SymbolKind.LocalConstant || symbol.kind == SymbolKind.Parameter || symbol.kind == SymbolKind.Variable) { // Local symbols cannot appear in any other files return result; } var allTextAssetGuids = FindAllTextAssets(); for (int i = allTextAssetGuids.Count; i --> 0; ) { var path = AssetDatabase.GUIDToAssetPath(allTextAssetGuids[i]); if (path != localAssetPath) if (!ignoreFileTypes.Contains(Path.GetExtension(path.ToLowerInvariant()))) assets.Add(AssetDatabase.GUIDToAssetPath(allTextAssetGuids[i])); } for (int i = assets.Count; i --> 0; ) result.Add(assets[i]); result.Sort((a, b) => { // Search .cs files first var extA = Path.GetExtension(a); if (extA.Equals(".cs", System.StringComparison.OrdinalIgnoreCase)) return -1; var extB = Path.GetExtension(b); if (extB.Equals(".cs", System.StringComparison.OrdinalIgnoreCase)) return 1; // Then .js and .boo files if (extA.Equals(".js", System.StringComparison.OrdinalIgnoreCase) || extA.Equals(".boo", System.StringComparison.OrdinalIgnoreCase)) return -1; if (extB.Equals(".js", System.StringComparison.OrdinalIgnoreCase) || extB.Equals(".boo", System.StringComparison.OrdinalIgnoreCase)) return 1; // And everything else at the end return 0; }); return result; }
/// <summary> /// we try all recursive definitions again and again /// until none of recursive definitions can be satisfied /// </summary> /// <param name="sd"></param> /// <param name="part"></param> /// <param name="tn"></param> /// <returns></returns> private TrackPart MatchRecursiveLines(SymbolDefinition sd, TrackPart part, TreeNode tn) { // TrackPart prevtrack = part; int subStartIndex = part.end + 1; TrackPart newTrack = null; TrackPart lastNew = null; do { // Try all recursive definitions. // If given recursive definition succeeded, then encapsulating TrackPart // is returned. Original part is inserted at first place in children. // If none of definitions succeeded, then original part is returned. newTrack = null; foreach (SymbolLineDefinition line in sd.recursive) { newTrack = MatchSymbolLineFromSecond(tn, line, subStartIndex); if (newTrack != null) { lastNew = newTrack; newTrack.symbolText = part.symbolText; newTrack.symbolType = part.symbolType; newTrack.position = part.position; newTrack.status = TrackStatus.MATCHED; newTrack.children.Insert(0, part); subStartIndex = newTrack.end + 1; part = newTrack; break; } } } while (newTrack != null); return part; }
/// <summary> /// Reads definition of BNF analyzer. Lines starting with /// 4 spaces are child lines to those /// that starts with letter /// </summary> /// <param name="script"></param> public void LoadText(string script) { SymbolDefinition symbol = null; string[] lines = script.Split('\r', '\n'); foreach(string line in lines) { if (line.Length > 0) { if (line.StartsWith(" ")) { if (symbol != null) { SymbolLineDefinition sd = new SymbolLineDefinition(); sd.SetString(line.Substring(4)); symbol.InsertLine(sd); } } else { symbol = new SymbolDefinition(); symbol.symbolText = line; symbolsList.Add(symbol); symbolsMap.Add(line, symbol); } } } }
public static bool IsValid(ref string expanded, SymbolDefinition context, FGGrammar.TokenSet expected) { var methodDef = context as MethodDefinition; var checkKeyword = false; for (var index = 0; (index = expanded.IndexOf('$', index)) != -1; ) { var end = expanded.IndexOf('$', index + 1); if (end < index) break; var macro = expanded.Substring(index + 1, end - index - 1); switch (macro) { case "MethodName": case "ArgumentList": if (methodDef == null) return false; break; case "ValidIfKeywordExpected": checkKeyword = true; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsStatement": if (expected != null && !expected.Matches(CsGrammar.Instance.tokenStatement)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "NotValidAsStatement": if (expected != null && expected.Matches(CsGrammar.Instance.tokenStatement)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsClassMember": if (expected != null && !expected.Matches(CsGrammar.Instance.tokenClassBody)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsStructMember": if (expected != null && !expected.Matches(CsGrammar.Instance.tokenStructBody)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsInterfaceMember": if (expected != null && !expected.Matches(CsGrammar.Instance.tokenInterfaceBody)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsNamespaceMember": if (expected != null && !expected.Matches(CsGrammar.Instance.tokenNamespaceBody)) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidAsTypeDeclaration": if (expected != null && !( expected.Matches(CsGrammar.Instance.tokenNamespaceBody) || expected.Matches(CsGrammar.Instance.tokenClassBody) || expected.Matches(CsGrammar.Instance.tokenStructBody) )) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidInMethodBody": if (methodDef == null) return false; expanded = expanded.Remove(index, end - index + 2); continue; case "ValidInPropertyBody": if (context == null || context.kind != SymbolKind.Property && (context.parentSymbol == null || context.parentSymbol.kind != SymbolKind.Property)) return false; expanded = expanded.Remove(index, end - index + 2); continue; } index = end + 1; } if (checkKeyword && expected != null) { var index = 0; while (expanded[index] >= 'a' && expanded[index] <= 'z') ++index; if (index == 0) { if (expanded.StartsWith("!=", System.StringComparison.Ordinal) || expanded.StartsWith("==", System.StringComparison.Ordinal)) index = 2; else return false; } var keyword = expanded.Substring(0, index); var tokenId = CsGrammar.Instance.TokenToId(keyword); if (!expected.Matches(tokenId)) return false; } return true; }
public static void Substitute(ref string part, SymbolDefinition context) { var methodDef = context as MethodDefinition; int index = 0; while ((index = part.IndexOf('$', index)) != -1) { var end = part.IndexOf('$', index + 1); if (end > index) { var macro = part.Substring(index + 1, end - index - 1); part = part.Remove(index, end - index + 1); switch (macro) { case "MethodName": if (methodDef == null) goto default; part = part.Insert(index, methodDef.name); break; case "ArgumentList": if (methodDef == null) goto default; part = part.Insert(index, string.Join(", ", ( from p in methodDef.GetParameters() select (p.IsOut ? "out " : p.IsRef ? "ref " : "") + p.GetName() ).ToArray())); break; default: part = part.Insert(index, macro); break; } } } }
public static IEnumerable<SnippetCompletion> EnumSnippets(SymbolDefinition context, FGGrammar.TokenSet expected, SyntaxToken tokenLeft, Scope scope) { foreach (var snippet in snippets) { var text = snippet.Value; if (IsValid(ref text, context, expected)) yield return new SnippetCompletion(snippet.Key + "..."); } if (snippetsProviders == null) { snippetsProviders = new List<ISnippetProvider>(); var types = typeof(CodeSnippets).Assembly.GetTypes(); foreach (var type in types) if (typeof(ISnippetProvider).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract) try { var instance = System.Activator.CreateInstance(type) as ISnippetProvider; snippetsProviders.Add(instance); } catch (System.Exception e) { Debug.LogException(e); } } foreach (var snippetsProvider in snippetsProviders) { foreach (var snippet in snippetsProvider.EnumSnippets(context, expected, tokenLeft, scope)) yield return snippet; } }
public static void FindAllReferences(SymbolDefinition symbol, string localAssetPath) { if (symbol.kind == SymbolKind.Accessor || symbol.kind == SymbolKind.Constructor || symbol.kind == SymbolKind.Destructor) symbol = symbol.parentSymbol; if (symbol == null) return; symbol = symbol.GetGenericSymbol(); var candidates = FindReferenceCandidates(symbol, localAssetPath); var searchOptions = new FindResultsWindow.SearchOptions { text = symbol.name, matchWord = true, matchCase = true, }; var candidateGuids = new string[candidates.Count]; for (int i = 0; i < candidates.Count; i++) candidateGuids[i] = AssetDatabase.AssetPathToGUID(candidates[i]); var searchForVarRefs = symbol is TypeDefinitionBase && symbol.kind != SymbolKind.Delegate; if (searchForVarRefs) { searchOptions.altText1 = "var"; var builtInTypesEnumerator = SymbolDefinition.builtInTypes.GetEnumerator(); for (var i = 0; i < 16; i++) { builtInTypesEnumerator.MoveNext(); var type = builtInTypesEnumerator.Current.Value; if (type == symbol) { searchOptions.altText2 = builtInTypesEnumerator.Current.Key; break; } } } FindResultsWindow resultsWindow = FindResultsWindow.Create( "References to " + symbol.FullName, FindAllInSingleFile, candidateGuids, searchOptions, "References"); resultsWindow.SetFilesValidator(ValidateFileForReferences); resultsWindow.SetResultsValidator(ValidateResultAsReference, symbol); }
public IEnumerable<SnippetCompletion> EnumSnippets( SymbolDefinition context, FGGrammar.TokenSet expectedTokens, SyntaxToken tokenLeft, Scope scope) { OverrideMethod.context = scope; if (tokenLeft == null || tokenLeft.parent == null || tokenLeft.parent.parent == null) yield break; if (tokenLeft.tokenKind != SyntaxToken.Kind.Keyword) yield break; if (tokenLeft.text != "override") yield break; var bodyScope = scope as BodyScope; if (bodyScope == null) yield break; var contextType = bodyScope.definition as TypeDefinitionBase; if (contextType == null || contextType.kind != SymbolKind.Class && contextType.kind != SymbolKind.Struct) yield break; var baseType = contextType.BaseType(); if (baseType == null || baseType.kind != SymbolKind.Class && baseType.kind != SymbolKind.Struct) yield break; var overrideMethodCandidates = new List<MethodDefinition>(); baseType.ListOverrideCandidates(overrideMethodCandidates, contextType.Assembly); if (overrideMethodCandidates.Count == 0) yield break; var textBuffer = FGTextBuffer.activeEditor.TextBuffer; var firstToken = tokenLeft.parent.parent.GetFirstLeaf().token; if (firstToken.formatedLine != tokenLeft.formatedLine) { firstToken = tokenLeft.formatedLine.tokens[0]; while (firstToken.tokenKind <= SyntaxToken.Kind.LastWSToken) firstToken = firstToken.formatedLine.tokens[firstToken.TokenIndex + 1]; } var tokenSpan = textBuffer.GetTokenSpan(firstToken.parent); OverrideMethod.overrideTextLength = FGTextBuffer.activeEditor.caretPosition.characterIndex - tokenSpan.StartPosition.index; foreach (var method in overrideMethodCandidates) { var methodGroup = contextType.FindName(method.name, -1, false) as MethodGroupDefinition; if (methodGroup != null) { bool skipThis = false; var signature = method.PrintParameters(method.GetParameters(), true); foreach (var m in methodGroup.methods) { if (method.NumTypeParameters == m.NumTypeParameters && signature == m.PrintParameters(m.GetParameters())) { skipThis = true; break; } } if (skipThis) continue; } var overrideCompletion = new OverrideMethod(method); yield return overrideCompletion; } }
public virtual object Visit(SymbolDefinition that, object value) { throw new System.NotImplementedException(); }