Esempio n. 1
0
        public void Visit(PyAst.FromImportStatement node)
        {
            var aliasPart     = node.AsNames is null ? "" : $" as {node.AsNames.Single()}";
            var isUsingStatic = node.Root.Names.Contains(CSharpToPythonConvert.UsingStaticMagicString);
            var modName       = FormatDottedName(
                node.Root,
                isUsingStatic ? new[] { CSharpToPythonConvert.UsingStaticMagicString } : Array.Empty <string>()
                );
            var usingStaticWarningComment = isUsingStatic ? " #ERROR: Was using static directive" : "";

            AppendLineWithIndentation($"from {modName} import *{aliasPart}{usingStaticWarningComment}");
        }
Esempio n. 2
0
		public PythonFromImport(IProjectContent projectContent, FromImportStatement fromImport)
			: base(projectContent)
		{
			this.fromImport = fromImport;
		}
Esempio n. 3
0
 public override void PostWalk(FromImportStatement node)
 {
     CommonPostWalk(node);
 }
Esempio n. 4
0
 public ImportFrom(FromImportStatement stmt)
     : this() {
     _module = stmt.Root.MakeString();
     _module = string.IsNullOrEmpty(_module) ? null : _module;
     _names = ConvertAliases(stmt.Names, stmt.AsNames);
     if (stmt.Root is RelativeModuleName)
         _level = ((RelativeModuleName)stmt.Root).DotCount;
 }
 // FromImportStatement
 public bool Walk(FromImportStatement node)
 {
     return Process(node);
 }
Esempio n. 6
0
        // 'from' relative_module 'import' identifier ['as' name] (',' identifier ['as' name]) *
        // 'from' relative_module 'import' '(' identifier ['as' name] (',' identifier ['as' name])* [','] ')'        
        // 'from' module 'import' "*"                                        
        private FromImportStatement ParseFromImportStmt() {
            Eat(TokenKind.KeywordFrom);
            SourceLocation start = GetStart();
            ModuleName dname = ParseRelativeModuleName();

            Eat(TokenKind.KeywordImport);

            bool ateParen = MaybeEat(TokenKind.LeftParenthesis);

            SymbolId[] names;
            SymbolId[] asNames;
            bool fromFuture = false;

            if (MaybeEat(TokenKind.Multiply)) {
                names = FromImportStatement.Star;
                asNames = null;

                if (dname is RelativeModuleName) {
                    ReportSyntaxError("'import *' not allowed with 'from .'");                         
                }
            } else {
                List<SymbolId> l = new List<SymbolId>();
                List<SymbolId> las = new List<SymbolId>();

                if (MaybeEat(TokenKind.LeftParenthesis)) {
                    ParseAsNameList(l, las);
                    Eat(TokenKind.RightParenthesis);
                } else {
                    ParseAsNameList(l, las);
                }
                names = l.ToArray();
                asNames = las.ToArray();
            }

            // Process from __future__ statement

            if (dname.Names.Count == 1 && dname.Names[0] == Symbols.Future) {
                if (!_fromFutureAllowed) {
                    ReportSyntaxError(IronPython.Resources.MisplacedFuture);
                }
                if (names == FromImportStatement.Star) {
                    ReportSyntaxError(IronPython.Resources.NoFutureStar);
                }
                fromFuture = true;
                foreach (SymbolId name in names) {
                    if (name == Symbols.Division) {
                        _languageFeatures |= PythonLanguageFeatures.TrueDivision;
                    } else if (name == Symbols.WithStmt) {
                        _languageFeatures |= PythonLanguageFeatures.AllowWithStatement;
                    } else if (name == Symbols.AbsoluteImport) {
                        _languageFeatures |= PythonLanguageFeatures.AbsoluteImports;
                    } else if (name == Symbols.PrintFunction && Python26) {
                        _languageFeatures |= PythonLanguageFeatures.PrintFunction;
                        _tokenizer.PrintFunction = true;
                    } else if (name == Symbols.UnicodeLiterals && Python26) {
                        // nop for us, just ignore it...
                    } else if (name == Symbols.NestedScopes) {
                    } else if (name == Symbols.Generators) {
                    } else {
                        string strName = SymbolTable.IdToString(name);
                        fromFuture = false;

                        if (strName != "braces") {
                            ReportSyntaxError(IronPython.Resources.UnknownFutureFeature + strName);
                        } else {
                            // match CPython error message
                            ReportSyntaxError(IronPython.Resources.NotAChance);
                        }
                    }
                }
            }

            if (ateParen) {
                Eat(TokenKind.RightParenthesis);
            }

            FromImportStatement ret = new FromImportStatement(dname, names, asNames, fromFuture, AbsoluteImports);
            ret.SetLoc(start, GetEnd());
            return ret;
        }
		public void FromSystemImportStatementFollowedByEmptySpaceHasModuleNameOfSystem()
		{
			string text = "from System import ";
			fromStatement = ParseStatement(text);
			Assert.AreEqual("System", fromStatement.Root.MakeString());
		}
Esempio n. 8
0
 // FromImportStmt
 public override bool Walk(FromImportStatement node) {
     if (node.Names != FromImportStatement.Star) {
         for (int i = 0; i < node.Names.Count; i++) {
             Define(node.AsNames[i] != null ? node.AsNames[i] : node.Names[i]);
         }
     }
     return true;
 }
 public virtual void PostWalk(FromImportStatement node)
 {
 }
 public override bool Walk(FromImportStatement node)
 {
     Emit(node); return false;
 }
 // FromImportStatement
 public virtual bool Walk(FromImportStatement node)
 {
     return true;
 }
Esempio n. 12
0
 // FromImportStmt
 public override bool Walk(FromImportStatement node)
 {
     if (node.Names != FromImportStatement.Star) {
         for (int i = 0; i < node.Names.Count; i++) {
             Define(node.AsNames[i] != SymbolTable.Empty ? node.AsNames[i] : node.Names[i]);
         }
     } else {
         Debug.Assert(current != null);
         current.ContainsImportStar = true;
     }
     return true;
 }
Esempio n. 13
0
        //| 'from' dotted_name 'import' ('*' | as_name_list | '(' as_name_list ')' )
        private FromImportStatement ParseFromImportStmt()
        {
            Eat(TokenKind.KeywordFrom);
            Location start = GetStart();
            DottedName dname = ParseDottedName();

            Eat(TokenKind.KeywordImport);

            IList<SymbolId> names;
            IList<SymbolId> asNames;
            bool fromFuture = false;

            if (MaybeEat(TokenKind.Multiply)) {
                names = FromImportStatement.Star;
                asNames = null;
            } else {
                List<SymbolId> l = new List<SymbolId>();
                List<SymbolId> las = new List<SymbolId>();

                if (MaybeEat(TokenKind.LeftParenthesis)) {
                    ParseAsNameList(l, las);
                    Eat(TokenKind.RightParenthesis);
                } else {
                    ParseAsNameList(l, las);
                }
                names = l.ToArray();
                asNames = las.ToArray();
            }

            // Process from __future__ statement

            if (dname.Names.Count == 1 && dname.Names[0] == SymbolTable.Future) {
                if (!fromFutureAllowed) {
                    ReportSyntaxError("from __future__ imports must occur at the beginning of the file");
                }
                if (names == FromImportStatement.Star) {
                    ReportSyntaxError("future statement does not support import *");
                }
                fromFuture = true;
                foreach (SymbolId name in names) {
                    if (name == SymbolTable.Division) {
                        context.TrueDivision = true;
                    } else if (Options.Python25 && name == SymbolTable.WithStmt) {
                        context.AllowWithStatement = true;
                    } else if (name == SymbolTable.NestedScopes) {
                    } else if (name == SymbolTable.Generators) {
                    } else {
                        fromFuture = false;
                        ReportSyntaxError(string.Format("future feature is not defined: {0}", name.GetString()));
                    }
                }
            }

            FromImportStatement ret = new FromImportStatement(dname, names, asNames, fromFuture);
            ret.SetLoc(GetExternal(), start, GetEnd());
            return ret;
        }
		public override bool Walk(FromImportStatement node)
		{
			PythonFromImport import = new PythonFromImport(compilationUnit.ProjectContent, node);
			compilationUnit.UsingScope.Usings.Add(import);
			return false;
		}
		public void FromSystemStatementWithNoImportHasModuleNameOfSystem()
		{
			string text = "from System";
			fromStatement = ParseStatement(text);
			Assert.AreEqual("System", fromStatement.Root.MakeString());
		}
        private CodeGen CompileModuleInit(CompilerContext context, GlobalSuite gs, TypeGen tg, string moduleName)
        {
            CodeGen init;
            if (!AutoImportAll) {
                init = OutputGenerator.GenerateModuleInitialize(context, gs, tg);
            } else {
                // auto-import all compiled modules, useful for CodeDom scenarios.
                init = OutputGenerator.GenerateModuleInitialize(context, gs, tg, staticTypes, delegate(CodeGen cg) {

                    Location dummyLocation = new Location(1, 1);

                    for (int i = 0; i < sourceFiles.Count; i++) {
                        string otherModName = GetModuleFromFilename(sourceFiles[i]);
                        if (otherModName == moduleName) continue;

                        FromImportStatement stmt = new FromImportStatement(
                            new DottedName(new SymbolId[] { SymbolTable.StringToId(otherModName) }),
                            FromImportStatement.Star, null);
                        stmt.Start = dummyLocation;
                        stmt.End = dummyLocation;
                        stmt.Emit(cg);
                    }

                    // Import the first part of all namespaces in all referenced assemblies

                    // First, determine the set of unique such prefixes
                    Dictionary<string, object> nsPrefixes = new Dictionary<string, object>();
                    foreach (string name in ReferencedAssemblies) {
                        Assembly a = LoadAssembly(name);

                        foreach (Type t in a.GetTypes()) {
                            // We only care about public types
                            if (!t.IsPublic) continue;

                            // Ignore types that don't have a namespace
                            if (t.Namespace == null) continue;

                            string nsPrefix = t.Namespace.Split('.')[0];
                            nsPrefixes[nsPrefix] = null;
                        }
                    }

                    // Import all the uniquer prefixes we found
                    foreach (string nsPrefix in nsPrefixes.Keys) {
                        SymbolId symbolId = SymbolTable.StringToId(nsPrefix);
                        cg.Names.CreateGlobalSlot(symbolId);
                        DottedName dottedName = new DottedName(new SymbolId[] { symbolId });
                        ImportStatement importStmt = new ImportStatement(
                            new DottedName[] { dottedName },
                            new SymbolId[] { SymbolTable.Empty });
                        importStmt.Start = dummyLocation;
                        importStmt.End = dummyLocation;
                        importStmt.Emit(cg);
                    }
                });
            }
            return init;
        }
		public void FromStatementFollowedBySpaceCharButNoModuleNameHasModuleNameOfEmptyString()
		{
			string text = "from ";
			fromStatement = ParseStatement(text);
			Assert.AreEqual(String.Empty, fromStatement.Root.MakeString());
		}
 public void PostWalk(FromImportStatement node)
 {
     PostProcess(node);
 }
		public void FromSystemImportStatementFollowedByIdentifierAsNameHasIdentifierAsNameInAsNamesCollection()
		{
			string text = "from System import abc as def";
			fromStatement = ParseStatement(text);
			Assert.AreEqual("def", fromStatement.AsNames[0]);
		}
Esempio n. 20
0
 // FromImportStatement
 public override bool Walk(FromImportStatement node)
 {
     if (node.Names != FromImportStatement.Star) {
         for (int i = 0; i < node.Names.Count; i++) {
             SymbolId name = node.AsNames[i] != SymbolTable.Empty ? node.AsNames[i] : node.Names[i];
             Define(name, new FromImportDefinition(node));
         }
     }
     return true;
 }
        public override bool Walk(FromImportStatement node)
        {
            var container = containers.Peek ();
            if (!container.SupportsFromStatements)
                return base.Walk (node);

            var fromImport = new PythonFromImport () {
                ModuleName = node.Root.MakeString (),
                Region = GetDomRegion (node)
            };

            // even if '*' is present, we may get an alias for a member
            // (using 'as')
            bool importAll = node.Names.Where (name => name == "*").Count () > 0;

            var names = new List<PythonNameReference> ();
            for (int i = 0; i < node.Names.Count; i++) {
                var name = node.Names [i];
                var asname = node.AsNames == null ? null : node.AsNames [i];

                // Discard unused data
                if (importAll && (String.IsNullOrEmpty (asname) || name == "*"))
                    continue;

                var nameRef = new PythonNameReference () {
                    Name = node.Names [i],
                    AsName = node.AsNames == null ? null : node.AsNames [i]
                };
                names.Add (nameRef);
            }

            fromImport.Names = names;
            fromImport.ImportAll = importAll;

            container.FromImports.Add (fromImport);

            return base.Walk (node);
        }
Esempio n. 22
0
 public override bool Walk(FromImportStatement node)
 {
     CommonWalk(node);
     return true;
 }
Esempio n. 23
0
 // FromImportStatement
 public override bool Walk(FromImportStatement node) {
     if (node.Names != FromImportStatement.Star) {
         PythonVariable[] variables = new PythonVariable[node.Names.Count];
         for (int i = 0; i < node.Names.Count; i++) {
             SymbolId name = node.AsNames[i] != SymbolId.Empty ? node.AsNames[i] : node.Names[i];
             variables[i] = DefineName(name);
         }
         node.Variables = variables;
     } else {
         Debug.Assert(_currentScope != null);
         _currentScope.ContainsImportStar = true;
         _currentScope.NeedsLocalsDictionary = true;
     }
     return true;
 }
Esempio n. 24
0
        // FromImportStatement
        public override bool Walk(FromImportStatement node)
        {
            node.Parent = _currentScope;

            if (node.Names != FromImportStatement.Star) {
                PythonVariable[] variables = new PythonVariable[node.Names.Count];
                node.Root.Parent = _currentScope;
                for (int i = 0; i < node.Names.Count; i++) {
                    string name = node.AsNames[i] != null ? node.AsNames[i] : node.Names[i];
                    variables[i] = DefineName(name);
                }
                node.Variables = variables;
            } else {
                Debug.Assert(_currentScope != null);
                _currentScope.ContainsImportStar = true;
                _currentScope.NeedsLocalsDictionary = true;
                _currentScope.HasLateBoundVariableSets = true;
            }
            return true;
        }
 public FromImportDefinition(FromImportStatement from)
 {
     this.from = from;
 }
Esempio n. 26
0
        // 'from' relative_module 'import' identifier ['as' name] (',' identifier ['as' name]) *
        // 'from' relative_module 'import' '(' identifier ['as' name] (',' identifier ['as' name])* [','] ')'        
        // 'from' module 'import' "*"                                        
        private FromImportStatement ParseFromImportStmt() {
            Eat(TokenKind.KeywordFrom);
            var start = GetStart();
            ModuleName dname = ParseRelativeModuleName();

            Eat(TokenKind.KeywordImport);

            bool ateParen = MaybeEat(TokenKind.LeftParenthesis);

            string[] names;
            string[] asNames;
            bool fromFuture = false;

            if (MaybeEat(TokenKind.Multiply)) {
                names = (string[])FromImportStatement.Star;
                asNames = null;
            } else {
                List<string> l = new List<string>();
                List<string> las = new List<string>();

                if (MaybeEat(TokenKind.LeftParenthesis)) {
                    ParseAsNameList(l, las);
                    Eat(TokenKind.RightParenthesis);
                } else {
                    ParseAsNameList(l, las);
                }
                names = l.ToArray();
                asNames = las.ToArray();
            }

            // Process from __future__ statement

            if (dname.Names.Count == 1 && dname.Names[0] == "__future__") {
                if (!_fromFutureAllowed) {
                    ReportSyntaxError(IronPython.Resources.MisplacedFuture);
                }
                if (names == FromImportStatement.Star) {
                    ReportSyntaxError(IronPython.Resources.NoFutureStar);
                }
                fromFuture = true;
                foreach (string name in names) {
                    if (name == "division") {
                        _languageFeatures |= ModuleOptions.TrueDivision;
                    } else if (name == "with_statement") {
                        _languageFeatures |= ModuleOptions.WithStatement;
                    } else if (name == "absolute_import") {
                        _languageFeatures |= ModuleOptions.AbsoluteImports;
                    } else if (name == "print_function") {
                        _languageFeatures |= ModuleOptions.PrintFunction;
                        _tokenizer.PrintFunction = true;
                    } else if (name == "unicode_literals") {
                        _tokenizer.UnicodeLiterals = true;
                        _languageFeatures |= ModuleOptions.UnicodeLiterals;
                    } else if (name == "nested_scopes") {
                    } else if (name == "generators") {
                    } else {
                        string strName = name;
                        fromFuture = false;

                        if (strName != "braces") {
                            ReportSyntaxError(IronPython.Resources.UnknownFutureFeature + strName);
                        } else {
                            // match CPython error message
                            ReportSyntaxError(IronPython.Resources.NotAChance);
                        }
                    }
                }
            }

            if (ateParen) {
                Eat(TokenKind.RightParenthesis);
            }

            FromImportStatement ret = new FromImportStatement(dname, (string[])names, asNames, fromFuture, AbsoluteImports);
            ret.SetLoc(_globalParent, start, GetEnd());
            return ret;
        }
Esempio n. 27
0
		public override bool Walk(FromImportStatement node)
		{
			writer.WriteLine("FromImport: " + node.Root.MakeString());
			return base.Walk(node);
		}