public virtual void Visit(DModule n) { VisitBlock(n); if (n.OptionalModuleStatement != null) n.OptionalModuleStatement.Accept(this); }
public static TypeReferencesResult Scan(DModule ast, ResolutionContext ctxt) { if (ast == null) return new TypeReferencesResult(); var typeRefFinder = new TypeReferenceFinder(ctxt); ContextFrame backupFrame = null; if(ctxt.ScopedBlock == ast) backupFrame = ctxt.Pop (); if (ctxt.CurrentContext == null) { ctxt.Push(backupFrame); backupFrame = null; } //typeRefFinder.ast = ast; // Enum all identifiers ast.Accept (typeRefFinder); if (backupFrame != null) ctxt.Push (backupFrame); // Crawl through all remaining expressions by evaluating their types and check if they're actual type references. /*typeRefFinder.queueCount = typeRefFinder.q.Count; typeRefFinder.ResolveAllIdentifiers(); */ return typeRefFinder.result; }
// http://www.digitalmars.com/d/2.0/module.html /// <summary> /// Module entry point /// </summary> public DModule Root() { Step(); var module = new DModule(); LastParsedObject = module; module.Location = la.Location; doc = module; // Only one module declaration possible! if (laKind == (Module)) { module.Description = GetComments(); module.OptionalModuleStatement= ModuleDeclaration(); module.Add(module.OptionalModuleStatement); module.Description += CheckForPostSemicolonComment(); if (module.OptionalModuleStatement.ModuleName!=null) module.ModuleName = module.OptionalModuleStatement.ModuleName.ToString(); module.OptionalModuleStatement.ParentNode = doc; } // Now only declarations or other statements are allowed! while (!IsEOF) { DeclDef(module); } // Also track comments at a module's end e.g. for multi-line comment folding GetComments(); module.EndLocation = la.Location; return module; }
public static TypeReferencesResult Scan(DModule ast, ParseCacheView pcl, ConditionalCompilationFlags compilationEnvironment = null) { if (ast == null) return new TypeReferencesResult(); var typeRefFinder = new OldTypeReferenceFinder(pcl, compilationEnvironment); typeRefFinder.ast = ast; // Enum all identifiers typeRefFinder.S(ast); // Crawl through all remaining expressions by evaluating their types and check if they're actual type references. typeRefFinder.queueCount = typeRefFinder.q.Count; typeRefFinder.ResolveAllIdentifiers(); return typeRefFinder.result; }
public static string FormatCode(string code, DModule ast = null, IDocumentAdapter document = null, DFormattingOptions options = null, ITextEditorOptions textStyle = null) { options = options ?? DFormattingOptions.CreateDStandard(); textStyle = textStyle ?? TextEditorOptions.Default; ast = ast ?? DParser.ParseString(code) as DModule; var formattingVisitor = new DFormattingVisitor(options, document ?? new TextDocument{ Text = code }, ast, textStyle); formattingVisitor.WalkThroughAst(); var sb = new StringBuilder(code); formattingVisitor.ApplyChanges((int start, int length, string insertedText) => { sb.Remove(start,length); sb.Insert(start,insertedText); }); return sb.ToString(); }
/// <summary> /// </summary> /// <param name="ast">The syntax tree to scan</param> /// <param name="symbol">Might not be a child symbol of ast</param> /// <param name="ctxt">The context required to search for symbols</param> /// <returns></returns> public static IEnumerable<ISyntaxRegion> Scan(DModule ast, INode symbol, ResolutionContext ctxt, bool includeDefinition = true) { if (ast == null || symbol == null || ctxt == null) return null; ctxt.PushNewScope(ast); var f = new ReferencesFinder(symbol, ast, ctxt); ast.Accept (f); ctxt.Pop(); var nodeRoot = symbol.NodeRoot as DModule; if (includeDefinition && nodeRoot != null && nodeRoot.FileName == ast.FileName) { var dc = symbol.Parent as DClassLike; if (dc != null && dc.ClassType == DSharp.Parser.DTokens.Template && dc.NameHash == symbol.NameHash) { f.l.Insert(0, new IdentifierDeclaration(dc.NameHash) { Location = dc.NameLocation, EndLocation = new CodeLocation(dc.NameLocation.Column + dc.Name.Length, dc.NameLocation.Line) }); } f.l.Insert(0, new IdentifierDeclaration(symbol.NameHash) { Location = symbol.NameLocation, EndLocation = new CodeLocation(symbol.NameLocation.Column + symbol.Name.Length, symbol.NameLocation.Line) }); } return f.l; }
/* public bool WaitForFinish(int millisecondsToWait = -1) { if(millisecondsToWait < 0) return completedEvent.WaitOne(); return completedEvent.WaitOne(millisecondsToWait); }*/ public void CacheModuleMethods(DModule ast, ResolutionContext ctxt) { foreach (var m in ast) if (m is DMethod) { var dm = (DMethod)m; if (dm.Parameters == null || dm.NameHash == 0 || dm.Parameters.Count == 0 || dm.Parameters[0].Type == null) continue; ctxt.PushNewScope(dm); var firstArg_result = TypeDeclarationResolver.Resolve(dm.Parameters[0].Type, ctxt); ctxt.Pop(); if (firstArg_result != null && firstArg_result.Length != 0) CachedMethods[dm] = firstArg_result[0]; } }
public void RemoveModuleMethods(DModule ast) { AbstractType t; if (ast != null) foreach (var m in ast) if (m is DMethod) CachedMethods.TryRemove (m as DMethod, out t); t = null; }
public void AddModule(DModule module, string nameOverride = null) { this.Add(module); }
bool ScanImportedModule(DModule module, MemberFilter VisibleMembers) { return scanChildren(module, VisibleMembers, true); }
public static bool RemoveModule (DModule module) { return RemoveModule (module, GetPackage (module)); }
public byte Visit(DModule n) { return(0); }
///// <summary> ///// Returns a name of default extension which is implemented by the library. ///// </summary> ///// <remarks>The first item (if any) is considered to be default extension for the library.</remarks> //public string DefaultExtension //{ // get { // string[] extensions = this.ImplementedExtensions; // if (extensions.Length > 0) // return extensions[0]; // else // return null; // } //} #endregion #region Construction /// <summary> /// Subclasses should have a parameter-less constructor. /// </summary> protected PhpLibraryDescriptor() { this.module = null; this.uniqueIndex = -1; this.configurationSectionName = null; }
public static bool AddOrUpdateModule (DModule module) { ModulePackage p; return AddOrUpdateModule (module, out p); }
internal void Invalidate() { this.configurationSectionName = null; this.module = null; this.uniqueIndex = -1; }
void PrepareQueue(DModule module) { if (module != null) foreach (var n in module) { var dm = n as DMethod; // UFCS only allows free function that contain at least one parameter if (dm == null || dm.NameHash == 0 || dm.Parameters.Count == 0 || dm.Parameters[0].Type == null) continue; queue.Push(dm); } }
ReferencesFinder(INode symbol, DModule ast, ResolutionContext ctxt) : base(ctxt) { this.symbol = symbol; searchHash = symbol.NameHash; }
protected void testComplete(DModule syntaxTree) { bool isSuccessful = false; if (currentResource != null) { isSuccessful = (currentErrors.Count == 0); if (!isSuccessful) { StringBuilder errors = new StringBuilder(); foreach (int lineNumber in currentErrors.Keys) { errors.AppendLine(currentErrors[lineNumber]); StringBuilder line = new StringBuilder(); line.Append(lineNumber.ToString().PadLeft(6, ' ')).Append(": ") .Append(currentResourceIsFile ? fetchLineFile(currentResource, lineNumber) : fetchLineResource(currentResource, lineNumber)); TestContext.WriteLine(line.ToString().Replace("{", "[").Replace("}", "]")); } throw new AssertFailedException(errors.ToString()); } Assert.IsNotNull(syntaxTree, "The syntax tree was not instantiated or not of the right type!"); TestContext.WriteLine(SerializeDNode(syntaxTree).Replace("{", "[").Replace("}", "]")); } }
public override IEnumerable <RootPackage> EnumRootPackagesSurroundingModule(DModule module) { return(packs); }
/// <summary> /// Finds the last import statement and returns its end location (the position after the semicolon). /// If no import but module statement was found, the end location of this module statement will be returned. /// </summary> public static CodeLocation FindLastImportStatementEndLocation(DModule m, string moduleCode = null) { IStatement lastStmt = null; foreach (var s in m.StaticStatements) if (s is ImportStatement) lastStmt = s; else if (lastStmt != null) break; if (lastStmt != null) return lastStmt.EndLocation; if (m.OptionalModuleStatement != null) return m.OptionalModuleStatement.EndLocation; if (moduleCode != null) using(var sr = new StringReader(moduleCode)) using (var lx = new Lexer(sr) { OnlyEnlistDDocComments = false }) { lx.NextToken(); if (lx.Comments.Count != 0) return lx.Comments[lx.Comments.Count - 1].EndPosition; } return new CodeLocation(1, 1); }
/// <summary> /// Parses the module again /// </summary> /// <param name="Module"></param> public static void UpdateModule(DModule Module) { var m = DParser.ParseFile(Module.FileName); Module.ParseErrors = m.ParseErrors; Module.AssignFrom(m); }
public ModuleSymbol(DModule mod, ISyntaxRegion td, PackageSymbol packageBase = null) : base(mod, packageBase, (IEnumerable<TemplateParameterSymbol>)null, td) { }
public static void UpdateModuleFromText(DModule Module, string Code) { var m = DParser.ParseString(Code); Module.ParseErrors = m.ParseErrors; Module.AssignFrom(m); }
public static ModulePackage GetPackage (DModule module, bool create = false) { if (module == null) return null; var root = GetRootPackage (module.FileName); if (root == null) return null; return root.GetOrCreateSubPackage (ModuleNameHelper.ExtractPackageName (module.ModuleName), create); }
/// <summary> /// Initializes and proceed parse procedure /// </summary> /// <param name="imports">List of imports in the module</param> /// <param name="ParseStructureOnly">If true, all statements and non-declarations are ignored - useful for analysing libraries</param> /// <returns>Completely parsed module structure</returns> public DModule Parse(bool ParseStructureOnly, bool KeepComments = true) { this.ParseStructureOnly = ParseStructureOnly; if(KeepComments) Lexer.OnlyEnlistDDocComments = false; doc=Root(); doc.ParseErrors = new System.Collections.ObjectModel.ReadOnlyCollection<ParserError>(ParseErrors); if(KeepComments){ doc.Comments = TrackerVariables.Comments.ToArray(); } return doc; }
public static bool AddOrUpdateModule (DModule module, out ModulePackage pack) { pack = null; if (module == null || string.IsNullOrEmpty (module.ModuleName)) return false; pack = GetPackage (module, true); if (pack == null) return false; var file = module.FileName; // Check if a module is already in the file lookup DModule oldMod; if (file != null && fileLookup.TryGetValue (file, out oldMod)) { RemoveModule (oldMod); oldMod = null; } pack.AddModule (module); fileLookup.Add (file, module); return true; }
public void Dispose() { doc = null; BlockAttributes.Clear(); BlockAttributes = null; DeclarationAttributes.Clear(); DeclarationAttributes = null; Lexer.Dispose(); Lexer = null; TrackerVariables = null; ParseErrors = null; }
internal static bool RemoveModule (DModule ast, ModulePackage pack) { if (ast == null || pack == null) return false; fileLookup.Remove (ast.FileName); if (!pack.RemoveModule (ast.ModuleName ?? "")) return false; ModulePackage parPack; if (pack.IsEmpty && (parPack = pack.Parent) != null) parPack.RemovePackage (pack.Name); return true; }
//INode typeNode; //IEnumerable<IAbstractSyntaxTree> moduleCache; public DDebugSymbolWrapper(DebugScopedSymbol sym, DDebugSupport support) : base(sym) { this.supp = support; try { /*var ci=CoreManager.DebugManagement.Engine.Symbols.GetPointerTarget(sym.Offset); * object mo = null; * IntPtr moPtr = new IntPtr(); * var raw = CoreManager.DebugManagement.Engine.Memory.ReadVirtual(ci, 4); * Marshal.StructureToPtr(raw, moPtr, false); * mo = Marshal.PtrToStructure(moPtr, typeof(DObject));*/ } catch { } // Search currently scoped module string file = ""; uint line = 0; CoreManager.DebugManagement.Engine.Symbols.GetLineByOffset(CoreManager.DebugManagement.Engine.CurrentInstructionOffset, out file, out line); codeLine = (int)line; if (string.IsNullOrWhiteSpace(file)) { return; } // If file name found, get syntax tree, as far as possible DProject ownerPrj = null; module = DLanguageBinding.GetFileSyntaxTree(file, out ownerPrj); // If syntax tree built, search the variable location if (module != null) { IStatement stmt = null; var block = DResolver.SearchBlockAt(module, new CodeLocation(0, codeLine), out stmt); var ctxt = ResolutionContext.Create(null, null, block); var res = TypeDeclarationResolver.ResolveIdentifier(Symbol.Name, ctxt, null); if (res != null && res.Length > 0 && res[0] is DSymbol) { variableNode = ((DSymbol)res[0]).Definition; //moduleCache = DCodeCompletionSupport.Instance.EnumAvailableModules(ownerPrj); } } // Set type string _typeString = base.TypeString; if (variableNode != null) { var t = variableNode.Type; if (t != null) { _typeString = t.ToString(); } } // Set value string if (_typeString.StartsWith("class ")) { _valueString = base.ValueString; //CodeInjection.WriteObjectVariable(supp.hProcess, supp.varAddr, (uint)sym.Offset); //_valueString = CodeInjection.EvaluateObjectString(supp.hProcess, supp.toStringFunc, supp.varAddr, (uint)sym.Offset); /* * var th = CodeInjection.BeginExecuteMethod(supp.hProcess, supp.toStringFunc); * * CoreManager.DebugManagement.Engine.Execute("~2 g"); * CoreManager.DebugManagement.Engine.WaitForEvent(); * * CodeInjection.WaitForExecutionEnd(th); */ //_valueString = CodeInjection.ReadDString(supp.hProcess, supp.varAddr); } else { _valueString = base.ValueString; if (variableNode != null) { ITypeDeclaration curValueType = variableNode.Type; if (curValueType != null) { if (!IsBasicType(curValueType)) { if (TypeString == "string") //TODO: Replace this by searching the alias definition in the cache { curValueType = new ArrayDecl() { InnerDeclaration = new DTokenDeclaration(DTokens.Char) } } ; else if (TypeString == "wstring") { curValueType = new ArrayDecl() { InnerDeclaration = new DTokenDeclaration(DTokens.Wchar) } } ; else if (TypeString == "dstring") { curValueType = new ArrayDecl() { InnerDeclaration = new DTokenDeclaration(DTokens.Dchar) } } ; if (IsArray(curValueType)) { var clampDecl = curValueType as ArrayDecl; var valueType = clampDecl.InnerDeclaration; if (valueType is DTokenDeclaration) { bool IsString = false; uint elsz = 0; var realType = DetermineArrayType((valueType as DTokenDeclaration).Token, out elsz, out IsString); var arr = CoreManager.DebugManagement.Engine.Symbols.ReadArray(sym.Offset, realType, elsz); if (arr != null) { _valueString = BuildArrayContentString(arr, IsString); } } } else { //TODO: call an object's toString method somehow to obtain its representing string manually } } } } } }