コード例 #1
0
        public TargetCodeResult Compile(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            TargetCodeResult result = new TargetCodeResult(aCurrentCodeLine);

            String superClassName = GetSupperClassName(aCurrentCodeLine);
            if (superClassName != null)
            {

                String classDef = GetClassDefinition(aCurrentCodeLine);

                StringBuilder newLine = new StringBuilder();
                if (classDef.StartsWith("class"))
                    newLine.Append("public ");

                newLine.Append(classDef);

                if (superClassName.IndexOf(",") > -1)
                    newLine.Append(" extends ").Append(GetExtendClass(superClassName)).Append(GetInterfaces(superClassName));
                else
                {
                    if (!superClassName.StartsWith("I"))
                        newLine.Append(" extends ").Append(superClassName);
                    else
                        newLine.Append(" implements ").Append(superClassName);
                }
                result = new TargetCodeResult(newLine.ToString());
            }

            return result;
        }
コード例 #2
0
 private ComparisonOperatorToken.OperatorType GetType(ref SourceCode code)
 {
     ComparisonOperatorToken.OperatorType t = ComparisonOperatorToken.OperatorType.Equals;
     if (code.Matches("=="))
     {
         t = ComparisonOperatorToken.OperatorType.Equals;
         code += 2;
     }
     if (code.Matches("!="))
     {
         t = ComparisonOperatorToken.OperatorType.NotEquals;
         code += 2;
     }
     if (code.Matches("<="))
     {
         t = ComparisonOperatorToken.OperatorType.LessThanOrEqual;
         code += 2;
     }
     if (code.Matches("<"))
     {
         t = ComparisonOperatorToken.OperatorType.LessThan;
         code++;
     }
     if (code.Matches(">="))
     {
         t = ComparisonOperatorToken.OperatorType.GreaterThanOrEqual;
         code += 2;
     }
     if (code.Matches(">"))
     {
         t = ComparisonOperatorToken.OperatorType.GreaterThan;
         code++;
     }
     return t;
 }
コード例 #3
0
 public override Token LateBuild(ScriptEngine engine, ref SourceCode sourceCode, ref Script script)
 {
     bool plus = _typeStack.Pop();
     var tokens = new List<Token>(engine.CurrentTokens);
     engine.CurrentTokens.Clear();
     return new PlusPlusMinusMinusToken(tokens, plus, true);
 }
コード例 #4
0
 private static String GetUsingNamespace(SourceCode aSourceCode, string aCurrentCodeLine)
 {
     String usingNamespace = aCurrentCodeLine;
     usingNamespace = aSourceCode.ReplaceKeyword(usingNamespace, "using", "").Trim();
     usingNamespace = usingNamespace.Replace(";", "").Trim();
     return usingNamespace;
 }
コード例 #5
0
        public TargetCodeResult Compile(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            String line = aCurrentCodeLine;
            if (aSourceCode.ContainKeyword(aCurrentCodeLine, "override"))
                line = aSourceCode.RemoveKeyword(line, "override");

            if (aSourceCode.ContainKeyword(aCurrentCodeLine, "virtual"))
                line = aSourceCode.RemoveKeyword(line,"virtual");

            if (aSourceCode.ContainKeyword(aCurrentCodeLine, "internal"))
                line = aSourceCode.ReplaceKeyword(line, "internal", "protected");

            if (aSourceCode.ContainKeyword(aCurrentCodeLine, "internal protected"))
                line = aSourceCode.ReplaceKeyword(line, "internal protected", "protected");

            StringBuilder newLine = new StringBuilder();

            newLine.Append(line);

            // TODO: We need to b able to indicate exception per method not just for all methods
            //if (aSourceCode.Arguments.ContainProgramArgument("throwexceptions"))
            //newLine.Append(" throws Exception");

            return new TargetCodeResult(newLine.ToString());
        }
コード例 #6
0
ファイル: RefField.cs プロジェクト: ktj007/mmo
 public override SourceCode GenerateReader(CodeContext context)
 {
     var code = new SourceCode();
     code.Append("this->skip(static_cast<msg_size_t>(sizeof(msg_type_t)));");
     code.Append("(*this) >> {0};", GetVarAccessor(context));
     return code;
 }
コード例 #7
0
        public TargetCodeResult Compile(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            TargetCodeResult result = new TargetCodeResult(aCurrentCodeLine);
            String usingNamespace = GetUsingNamespace(aSourceCode, aCurrentCodeLine);

            bool correctLine = IsUsingCorrect(usingNamespace);

            if (!correctLine && (IsSystemNamespace(usingNamespace) || IsProgramNamespace(aSourceCode, usingNamespace)))
                return new TargetCodeResult("");

            if (correctLine)
            {
                // TODO: For now we import all the Java classes in that package, we don't worry much about that since the Java compiler will take care of this for us
                // Suggest that we do change this in the future if required
                StringBuilder newLine = new StringBuilder();
                newLine.Append("import ").Append(usingNamespace).Append(".*;");
                result = new TargetCodeResult(newLine.ToString());
            }
            else
            {
                StringBuilder newLine = new StringBuilder();
                newLine.Append("//");
                newLine.Append(aCurrentCodeLine);
                newLine.Append("  // Not supported yet");
                result = new TargetCodeResult(newLine.ToString());
                result.LogError(aSourceCode.GetFileName() + ": Using directive not supported yet on line: " + aLinePosition);
            }
            return result;
        }
コード例 #8
0
        /// <summary>
        /// Extracts the body of the given preprocessor directive symbol, parses it, and returns the parsed expression.
        /// </summary>
        /// <param name="parser">
        /// The C# parser.
        /// </param>
        /// <param name="sourceCode">
        /// The source code containing the preprocessor directive symbol.
        /// </param>
        /// <param name="preprocessorSymbol">
        /// The preprocessor directive symbol.
        /// </param>
        /// <param name="startIndex">
        /// The index of the start of the expression body within the text string.
        /// </param>
        /// <returns>
        /// Returns the expression.
        /// </returns>
        internal static Expression GetConditionalPreprocessorBodyExpression(CsParser parser, SourceCode sourceCode, Symbol preprocessorSymbol, int startIndex)
        {
            Param.AssertNotNull(parser, "parser");
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.AssertNotNull(preprocessorSymbol, "preprocessorSymbol");
            Param.AssertGreaterThanOrEqualToZero(startIndex, "startIndex");
            Debug.Assert(preprocessorSymbol.SymbolType == SymbolType.PreprocessorDirective, "The symbol is not a preprocessor directive.");

            string text = preprocessorSymbol.Text.Substring(startIndex, preprocessorSymbol.Text.Length - startIndex).Trim();
            if (text.Length > 0)
            {
                using (StringReader reader = new StringReader(text))
                {
                    // Extract the symbols within this text.
                    CodeLexer lexer = new CodeLexer(parser, sourceCode, new CodeReader(reader));
                    List<Symbol> symbolList = lexer.GetSymbols(sourceCode, null);
                    SymbolManager directiveSymbols = new SymbolManager(symbolList);

                    CodeParser preprocessorBodyParser = new CodeParser(parser, directiveSymbols);

                    // Parse these symbols to create the body expression.
                    return preprocessorBodyParser.GetNextConditionalPreprocessorExpression(sourceCode);
                }
            }

            // The directive has no body.
            return null;
        }
コード例 #9
0
 public static bool IdentifyMainMethod(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
 {
     bool result = false;
     if (aSourceCode.ContainKeyword(aCurrentCodeLine, "static") && aCurrentCodeLine.IndexOf("Main") > -1  && (aCurrentCodeLine.EndsWith("{") || aSourceCode.GetNextLine(aLinePosition).StartsWith("{")))
         result = true;
     return result;
 }
コード例 #10
0
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            while ((++sourceCode).SpecialChar)
            {
            }
            if (sourceCode.Peek() != '{')
            {
                sourceCode.Throw(String.Format("Error parsing a 'do' statement, expected a '{' but got '{0}' instead.",
                                               sourceCode.Peek()));
            }
            List<List<List<Token>>> code = engine.BuildLongTokens(ref sourceCode, ref script, new[] {'}'});

            if (!sourceCode.SeekToNext("while"))
            {
                sourceCode.Throw("Error parsing a 'do' statement, was expecting a 'while' after the { } block.");
            }

            if (!sourceCode.SeekToNext('('))
            {
                sourceCode.Throw("Error parsing a 'do' statement, was expecting a '(' after 'while'.");
            }

            List<List<Token>> exitCondition = engine.BuildTokensAdvanced(ref sourceCode, ref script, new[] {')'});

            return new DoWhileToken(code, exitCondition);
        }
コード例 #11
0
        public TargetCodeResult Compile(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            TargetCodeResult result = new TargetCodeResult(aCurrentCodeLine);

            int propertyNameLocationInCode = 0;

            String propertyName = GetPropertyName(aCurrentCodeLine, out propertyNameLocationInCode);
            String propertyType = GetPropertyType(aCurrentCodeLine, propertyNameLocationInCode);

            String memberVariableName = "_" + propertyName.ToLower();
            String parameterName = "a" + propertyName;

            StringBuilder newLine = new StringBuilder();
            newLine.Append("\n");
            newLine.Append("private ").Append(propertyType).Append(" ").Append(memberVariableName).Append(";\n\n");
            newLine.Append("public").Append(" ").Append(propertyType).Append(" ").Append("get").Append(propertyName).Append("()\n");
            newLine.Append("{\n");
            newLine.Append("return this.").Append(memberVariableName).Append(";\n");
            newLine.Append("}");
            newLine.Append("\n\n");
            newLine.Append("public void ").Append("set").Append(propertyName).Append("(").Append(propertyType).Append(" ").Append(parameterName).Append(")").Append("\n");
            newLine.Append("{\n");
            newLine.Append("this.").Append(memberVariableName).Append(" = ").Append(parameterName).Append(";\n");
            newLine.Append("}\n");

            result = new TargetCodeResult(newLine.ToString());

            return result;
        }
コード例 #12
0
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            // while (condition) { /* Code */ }
            sourceCode += 4; // The +1 comes from below.

            while ((++sourceCode).SpecialChar)
            {
            }

            if (sourceCode.CurrentCode != '(')
            {
                sourceCode.Throw("Error parsing a 'while' statement, was epexting a '(' after 'while'.");
            }

            List<List<Token>> exitCondition = engine.BuildTokensAdvanced(ref sourceCode, ref script, new[] {')'});

            if (!sourceCode.SeekToNext('{'))
            {
                sourceCode.Throw(String.Format("Unexpected char: '{0}'", sourceCode.CurrentCode));
            }

            List<List<List<Token>>> code = engine.BuildLongTokens(ref sourceCode, ref script, new[] {'}'});

            return new WhileLoopToken(exitCondition, code);
        }
コード例 #13
0
ファイル: RefListField.cs プロジェクト: ktj007/mmo
 public override SourceCode GenerateField(CodeContext context)
 {
     var code = new SourceCode();
     code.Append("typedef std::vector<{0}> {1};", CanonicalTarget, TypeName);
     code.Append("{0} {1};", TypeName, VarName);
     return code;
 }
コード例 #14
0
        private void InitializeWizard(SourceCode.Framework.WizardInitializeArgs e)
        {
            PowerShellEvent eventObj = null;

            switch (base.Status)
            {
                case WizardStatus.New:
                case WizardStatus.NewDelayed:
                    eventObj = new PowerShellEvent();
                    eventObj.WizardDefinition = base.Definition;
                    SourceCode.Workflow.Wizards.WizardHelper.GetEventActivity(e.Parent).Events.Insert(e.InsertIndex, eventObj);
                    if (base.Status == WizardStatus.NewDelayed)
                    {
                        return;
                    }
                    break;
                case WizardStatus.Executed:
                case WizardStatus.Delayed:
                    if (e.Parent is PowerShellEvent)
                    {
                        eventObj = (PowerShellEvent)e.Parent;
                    }
                    break;
            }

            base.Pages.Add(new Pages.Start());
            base.Pages.Add(new Pages.InputVariables(eventObj));
            base.Pages.Add(new Pages.PowerShellScript(eventObj));
            base.Pages.Add(new Pages.OutputVariables(eventObj));
            base.Pages.Add(new Pages.Finish());
        }
コード例 #15
0
 public override bool ConditionMatch(Token lastToken, SourceCode sourceCode)
 {
     if (lastToken == null)
     {
         return sourceCode.CurrentCode == '[';
     }
     return false;
 }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the CsDocumentWrapper class.
        /// </summary>
        /// <param name="parser">The parser.</param>
        /// <param name="sourceCode">The original source code.</param>
        public CsDocumentWrapper(CsParser parser, SourceCode sourceCode) 
        {
            Param.AssertNotNull(parser, "parser");
            Param.AssertNotNull(sourceCode, "sourceCode");

            this.parser = parser;
            this.sourceCode = sourceCode;
        }
コード例 #17
0
        public bool Identify(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            bool result = false;
            if (aSourceCode.ContainKeyword(aCurrentCodeLine, "get;") || aSourceCode.ContainKeyword(aCurrentCodeLine, "set;"))
                result = true;

            return result;
        }
コード例 #18
0
 internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack)
 {
     dynamic result = PropertyNameAndExpression(stack);
     if (result.PropertyName == Constants.KeyWords.Pop)
         Environment(state).Push(result.Expression);
     else
         Environment(state)[result.PropertyName] = result.Expression;
 }
コード例 #19
0
        public bool Identify(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            bool result = false;
            if (aCurrentCodeLine.StartsWith("using") && aCurrentCodeLine.IndexOf("{") == -1 && !aSourceCode.GetNextLine(aLinePosition).StartsWith("{"))
                result = true;

            return result;
        }
コード例 #20
0
        private bool IsProgramNamespace(SourceCode aSourceCode, string aUsingNamespace)
        {
            var found = (from code in aSourceCode.GetLines()
                         where code.StartsWith("namespace") && aSourceCode.ContainKeyword(code, aUsingNamespace)
                         select code).FirstOrDefault();

            return found != null;
        }
コード例 #21
0
 public override bool ConditionMatch(Token lastToken, SourceCode sourceCode)
 {
     if (sourceCode.CurrentCode == '-' && char.IsNumber(sourceCode.Peek(true)))
     {
         return true;
     }
     return char.IsNumber(sourceCode.Script, sourceCode.Offset);
 }
コード例 #22
0
ファイル: NotBuilder.cs プロジェクト: iammitch/Slimterpreter
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            sourceCode++;

            engine.AddPostBuildOperation(new NotToken.NotPass(), 1000);

            return new NotToken();
        }
コード例 #23
0
 public override bool ConditionMatch(Token lastToken, SourceCode sourceCode)
 {
     if (lastToken is NewTypeToken || lastToken is TypeFunctionToken)
     {
         // TODO: Fix this problem, as if the method returns a Function, () won't work!
         return false;
     }
     return sourceCode.Matches("(");
 }
コード例 #24
0
        public bool Identify(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            bool result = false;

            if (aCurrentCodeLine.StartsWith("}") && !aSourceCode.IsThereMoreCode(aLinePosition))
                result = true;

            return result;
        }
コード例 #25
0
ファイル: TypeBuilder.cs プロジェクト: iammitch/Slimterpreter
 public override bool ConditionMatch(Token lastToken, SourceCode sourceCode)
 {
     // {TypeID}
     if (char.IsLetter(sourceCode.CurrentCode))
     {
         return true;
     }
     return false;
 }
コード例 #26
0
        public TargetCodeResult Compile(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            StringBuilder newLine = new StringBuilder();

            newLine.Append("public static void main(String[] args)");
            if (aCurrentCodeLine.EndsWith("{"))
                newLine.Append(" { ");
            return new TargetCodeResult(newLine.ToString());
        }
コード例 #27
0
ファイル: InBuilder.cs プロジェクト: iammitch/Slimterpreter
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            sourceCode += 2;

            // Add a post build operation to build this.
            engine.AddPostBuildOperation(new InToken.InTokenPass(), 10000);

            return new InToken();
        }
コード例 #28
0
        public bool Identify(SourceCode aSourceCode, string aCurrentCodeLine, int aLinePosition)
        {
            bool result = false;

            if (aCurrentCodeLine.StartsWith("{") && aSourceCode.GetPreviousLine(aCurrentCodeLine, aLinePosition).StartsWith("namespace"))
                result = true;

            return result;
        }
コード例 #29
0
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            string text = "";
            bool space = false;
            bool isFloat = false;

            if (sourceCode.CurrentCode == '-')
            {
                text = "-";
                sourceCode++;
                while (sourceCode.SpecialChar)
                {
                    sourceCode++;
                }
            }

            while (!sourceCode.EOF && !engine.IsStatementEnd(sourceCode.CurrentCode, true))
            {
                if (sourceCode.CurrentCode == ' ')
                {
                    space = true;
                }
                else
                {
                    if (space)
                    {
                        throw new Exception("Unexpected Whitespace");
                    }
                    if (sourceCode.CurrentCode == '.')
                    {
                        if (!char.IsNumber(sourceCode.GetOffset(1)))
                        {
                            break;
                        }
                    }
                    if (sourceCode.CurrentCode == 'f' || sourceCode.CurrentCode == 'F')
                    {
                        isFloat = true;
                    }
                    else
                    {
                        if (isFloat)
                        {
                            throw new Exception("Expected ending condition.");
                        }
                        text += sourceCode.CurrentCode;
                    }
                }
                sourceCode++;
            }
            if (sourceCode.EOF)
            {
                throw new Exception("Unexpected EOF");
            }
            return new ObjectToken<Number>(new Number(double.Parse(text)));
        }
コード例 #30
0
 private void CreateSourceCodeFile(String filePath, SourceCode sourceCode)
 {
     using (var stm = new FileStream(filePath, FileMode.Create))
     {
         var cs = new CSharpSourceCodeGenerator(new StreamWriter(stm));
         cs.Write(sourceCode);
         cs.Flush();
         stm.Close();
     }
 }
コード例 #31
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A new StringBasedSourceCode object.
        /// </returns>
        public SourceCode Create(string path, CodeProject project, SourceParser parser, object context)
        {
            StyleCopTrace.In();

            string source = (string)context;

            SourceCode sourceCode = source == null ? (SourceCode) new CodeFile(path, project, parser) : new StringBasedSourceCode(project, parser, path, source);

            return(StyleCopTrace.Out(sourceCode));
        }
コード例 #32
0
ファイル: CsDocument.cs プロジェクト: longzai2651/StyleCop2
        /// <summary>
        /// Initializes a new instance of the CsDocument class.
        /// </summary>
        /// <param name="sourceCode">
        /// The source code that this document represents.
        /// </param>
        /// <param name="parser">
        /// The parser that is creating this object.
        /// </param>
        /// <param name="tokens">
        /// The tokens in the document.
        /// </param>
        internal CsDocument(SourceCode sourceCode, CsParser parser, MasterList <CsToken> tokens)
            : base(sourceCode)
        {
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.AssertNotNull(parser, "parser");
            Param.Ignore(tokens);

            this.parser = parser;
            this.tokens = tokens;
        }
コード例 #33
0
ファイル: CaDETMember.cs プロジェクト: Ana00000/platform
 public bool IsFieldDefiningAccessor()
 {
     //TODO: This is a workaround that should be reworked https://stackoverflow.com/questions/64009302/roslyn-c-how-to-get-all-fields-and-properties-and-their-belonging-class-acce
     //TODO: It is specific to C# properties. Should move this to CSharpCodeParser so that each language can define its rule for calculating simple accessors.
     //In its current form, this function will return true for simple properties (e.g., public int SomeNumber { get; set; })
     return(Type.Equals(CaDETMemberType.Property) &&
            (InvokedMethods.Count == 0) &&
            (AccessedAccessors.Count == 0 && AccessedFields.Count == 0) &&
            !SourceCode.Contains("return ") && !SourceCode.Contains("="));
 }
コード例 #34
0
ファイル: DataClass.cs プロジェクト: jingjing54007/mmo
        public SourceCode GenerateDependencyIncludeCode()
        {
            var code = new SourceCode();

            foreach (var clazz in ReferencingChildClass)
            {
                code.Append("#include \"{0}\"", clazz.HeaderFileName);
            }
            return(code);
        }
コード例 #35
0
ファイル: CodeLexer.cs プロジェクト: katerina-marchenkova/my
        /// <summary>
        /// Initializes a new instance of the CodeLexer class.
        /// </summary>
        /// <param name="parser">The C# parser.</param>
        /// <param name="source">The source to read.</param>
        /// <param name="codeReader">Used for reading the source code.</param>
        internal CodeLexer(CsParser parser, SourceCode source, CodeReader codeReader)
        {
            Param.AssertNotNull(parser, "parser");
            Param.AssertNotNull(source, "source");
            Param.AssertNotNull(codeReader, "codeReader");

            this.parser = parser;
            this.source = source;
            this.codeReader = codeReader;
        }
コード例 #36
0
        public void InitializeArrayVariable(DataType dataType, string name, int length)
        {
            if (!(dataType is RefType type))
            {
                throw new ArgumentException($"{nameof(dataType)} needs to be a reference type");
            }

            if (!DataTypes.Types[DataTypes.arrayTypes].Any(x => x.Name == dataType.Name))
            {
                throw new InvalidOperationException($"{dataType.Name} is in an array type.");
            }

            if (!Types.Any(x => x.Name == type.Name))
            {
                throw new InvalidOperationException($"{dataType.Name} is not in the list of available types.");
            }

            if (Variables.Any(x => x.Name == name))
            {
                throw new InvalidOperationException($"Variable with name {name} already exists");
            }

            var variable = new Variable
            {
                Name  = name,
                Type  = dataType,
                Value = NextAvailableHeap.ToString()
            };

            var valueType = GetValueTypeFromArray(dataType.Name);

            for (int i = 0; i < length; i++)
            {
                var variableOnHeap = new Variable
                {
                    Name   = $"{name}[{i}]",
                    Type   = valueType,
                    Value  = valueType.Defaultvalue,
                    Parent = variable
                };

                variable.Variables.Add(variableOnHeap);

                Ram.SetVariable(NextAvailableHeap, variableOnHeap);
                NextAvailableHeap++;
            }

            Ram.SetVariable(NextAvailableStack, variable);

            Variables.Add(variable);

            NextAvailableStack++;

            SourceCode.Add($"{dataType.Name} {name} = new {valueType.Name}[{length}];");
        }
コード例 #37
0
ファイル: CsParser.cs プロジェクト: MuthukumarA/StyleCop
        /// <summary>
        /// Indicates whether to skip analysis on the given document.
        /// </summary>
        /// <param name="sourceCode">
        /// The document.
        /// </param>
        /// <returns>
        /// Returns true to skip analysis on the document.
        /// </returns>
        public override bool SkipAnalysisForDocument(SourceCode sourceCode)
        {
            Param.RequireNotNull(sourceCode, "sourceCode");

            if (sourceCode == null || sourceCode.Name == null ||
                !this.FileTypes.Contains(Path.GetExtension(sourceCode.Name).Trim('.').ToUpperInvariant()))
            {
                return(true);
            }

            // Get the property indicating whether to analyze designer files.
            BooleanProperty analyzeDesignerFilesProperty = this.GetSetting(sourceCode.Settings, AnalyzeDesignerFilesProperty) as BooleanProperty;

            // Default the setting to true if it does not exist.
            bool analyzeDesignerFiles = true;

            if (analyzeDesignerFilesProperty != null)
            {
                analyzeDesignerFiles = analyzeDesignerFilesProperty.Value;
            }

            if (analyzeDesignerFiles || !sourceCode.Name.EndsWith(".Designer.cs", StringComparison.OrdinalIgnoreCase))
            {
                // Get the property indicating whether to analyze generated files.
                BooleanProperty analyzerGeneratedFilesProperty = this.GetSetting(sourceCode.Settings, AnalyzeGeneratedFilesProperty) as BooleanProperty;

                // Default the setting to false if it does not exist.
                bool analyzeGeneratedFiles = false;
                if (analyzerGeneratedFilesProperty != null)
                {
                    analyzeGeneratedFiles = analyzerGeneratedFilesProperty.Value;
                }

                if (analyzeGeneratedFiles)
                {
                    // This document should be analyzed.
                    return(false);
                }

                // Initialize to the default set of generated file filters.
                IEnumerable <string> filters = DefaultGeneratedFileFilters;

                // Get the file filter list for generated files.
                CollectionProperty generatedFileFilterSettings = this.GetSetting(sourceCode.Settings, GeneratedFileFiltersProperty) as CollectionProperty;

                if (generatedFileFilterSettings != null)
                {
                    filters = generatedFileFilterSettings.Values;
                }

                return(Utils.InputMatchesRegExPattern(sourceCode.Path, filters));
            }

            return(true);
        }
コード例 #38
0
        /// <summary>
        /// Loads and restores the serialized state of the current instance, if available
        /// </summary>
        /// <param name="file">The optional file to load, if present</param>
        public async Task RestoreStateAsync(IFile?file)
        {
            if (file is null)
            {
                string
                    temporaryPath = FilesService.TemporaryFilesPath,
                    statePath     = Path.Combine(temporaryPath, "state.json");

                if (!(await FilesService.TryGetFileFromPathAsync(statePath) is IFile jsonFile))
                {
                    return;
                }

                using Stream stream = await jsonFile.OpenStreamForReadAsync();

                using StreamReader reader = new StreamReader(stream);

                string json = await reader.ReadToEndAsync();

                IdeState state = JsonSerializer.Deserialize <IdeState>(json);

                if (state.FilePath is null)
                {
                    Code = SourceCode.CreateEmpty();
                }
                else
                {
                    IFile?sourceFile = await FilesService.TryGetFileFromPathAsync(state.FilePath);

                    if (sourceFile is null)
                    {
                        Code = SourceCode.CreateEmpty();
                    }
                    else
                    {
                        Code = await SourceCode.TryLoadFromEditableFileAsync(sourceFile) ?? SourceCode.CreateEmpty();
                    }
                }

                Text   = state.Text.AsMemory();
                Row    = state.Row;
                Column = state.Column;

                if (!(Code.File is null))
                {
                    _ = FilesHistoryService.LogOrUpdateActivityAsync(Code.File);
                }

                StateRestored?.Invoke(this, state);
            }
            else
            {
                await TryLoadTextFromFileAsync(file);
            }
        }
コード例 #39
0
        public IEnumerable <Token> LexFile(SourceCode sourceCode)
        {
            this.sourceCode = sourceCode;
            builder.Clear();
            line   = 1;
            index  = 0;
            column = 0;
            CreateToken(TokenKind.EndOfFile);

            return(LexContents());
        }
コード例 #40
0
 public Location getGeneratedSourceCodeMethodLineOffset()
 {
     if (CreatedFromSnipptet && SourceCode.valid())
     {
         if (AstDetails.Methods.size() > 0)
         {
             return(AstDetails.Methods[0].OriginalObject.firstLineOfCode());
         }
     }
     return(new Location(0, 0));
 }
コード例 #41
0
ファイル: Lexer.cs プロジェクト: sampath1983jan/TechData
 /// <summary>
 ///
 /// </summary>
 /// <param name="sourceCode"></param>
 /// <returns></returns>
 public IEnumerable <Token> LexFile(SourceCode sourceCode)
 {
     _sourceCode = sourceCode;
     _builder.Clear();
     _line       = 1;
     _index      = 0;
     _column     = 0;
     _tokenStart = new SourceLocation(0, _line, 0);
     //   CreateToken(TokenKind.EndOfFile);
     return(LexContents());
 }
コード例 #42
0
ファイル: Lexer.cs プロジェクト: Thourum/zLisp
        public IEnumerable <Token> LexFile(SourceCode sourceCode)
        {
            _sourceCode = sourceCode;
            _builder.Clear();
            _line       = 1;
            _index      = 0;
            _column     = 0;
            _tokenStart = new SourceLocation(_index, _line, _column);

            return(LexContents());
        }
コード例 #43
0
ファイル: DataClass.cs プロジェクト: jingjing54007/mmo
        public SourceCode GenerateParseDeclsCode()
        {
            var code = new SourceCode();

            code.Append(GenerateParseDeclCode());
            foreach (var field in DataClassFields)
            {
                code.Append(field.Class.GenerateParseDeclCode());
            }
            return(code);
        }
コード例 #44
0
        /// <summary>
        /// Tries to open and load a source code file
        /// </summary>
        /// <param name="file">The file to open</param>
        private async Task TryLoadTextFromFileAsync(IFile file)
        {
            if (await SourceCode.TryLoadFromEditableFileAsync(file) is SourceCode code)
            {
                Code = code;

                _ = FilesHistoryService.LogOrUpdateActivityAsync(code.File !);

                CodeLoaded?.Invoke(this, Code.Content);
            }
        }
コード例 #45
0
        internal void updateSources(ComponentType ct, Component c)
        {
            LoadBodyItems(ct.componentInfo);

            IDictionary <string, Unit> units = new Dictionary <string, Unit>();

            AbstractComponentFunctorApplication absCapp = br.ufc.pargo.hpe.backend.DGAC.BackEnd.acfadao.retrieve(c.Id_functor_app);

            int id_abstract = absCapp.Id_abstract;

            // for each unit ...
            foreach (UnitType u in unit)
            {
                string uref = u.uRef;
                string iRef = u.iRef;
                //string urefSuper = u.super == null ? null : u.super.uRef;
                int partition_index = u.replicaSpecified ? u.replica : 0;

                Interface     i  = br.ufc.pargo.hpe.backend.DGAC.BackEnd.idao.retrieve(id_abstract, uref);
                InterfaceType ui = lookForInterface(iRef);

                foreach (SourceFileType sft in ui.sources[ui.sources.Length - 1].file)
                {
                    SourceCode ss = new SourceCode();
                    ss.Type_owner         = 'u';
                    ss.Id_owner_container = c.Id_concrete;
                    ss.Id_owner           = uref;
                    ss.Contents           = sft.contents;
                    ss.File_type          = sft.srcType.Equals("user") || sft.srcType.Equals("base") ? "dll" : "platform.settings";
                    ss.File_name          = sft.name;
                    br.ufc.pargo.hpe.backend.DGAC.BackEnd.scdao.update(ss);
                    if (sft.externalDependency != null)
                    {
                        foreach (string extRef in sft.externalDependency)
                        {
                            SourceCodeReference ssr = new SourceCodeReference();
                            ssr.Type_owner         = ss.Type_owner;
                            ssr.Id_owner_container = ss.Id_owner_container;
                            ssr.Id_owner           = ss.Id_owner;
                            ssr.File_name          = ss.File_name;
                            ssr.Reference          = extRef;
                            if (br.ufc.pargo.hpe.backend.DGAC.BackEnd.scrdao.retrieve(ssr) != null)
                            {
                                // DGAC.BackEnd.scrdao.update(ssr);
                            }
                            else
                            {
                                br.ufc.pargo.hpe.backend.DGAC.BackEnd.scrdao.insert(ssr);
                            }
                        }
                    }
                }
            }
        }
コード例 #46
0
        public override int CalculateNumberOfClasses()
        {
            int counter = 0;

            SourceCode.Split('\n').ToList().ForEach(delegate(string line) {
                if (line.Contains(" class "))
                {
                    counter++;
                }
            });
            return(Metrics.NumberOfClasses = counter);
        }
コード例 #47
0
        //public Expression ParseExpression(SourceCode sourceCode, IEnumerable<Token> tokens)
        //{
        //    InitializeParser(sourceCode, tokens, GlassScriptParserOptions.OptionalSemicolons);
        //    try
        //    {
        //        return ParseExpression();
        //    }
        //    catch (SyntaxException)
        //    {
        //        // Errors are located in the ErrorSink.
        //        return null;
        //    }
        //}

        //public SourceDocument ParseFile(SourceCode sourceCode, IEnumerable<Token> tokens)
        //{
        //    return ParseFile(sourceCode, tokens, GlassScriptParserOptions.Default);
        //}

        public dynamic ParseFile(SourceCode sourceCode, IEnumerable <Token> tokens)
        {
            InitializeParser(sourceCode, tokens);
            try
            {
                return(ParseDocument());
            }
            catch (SyntaxException)
            {
                return(null);
            }
        }
        internal void updateSources(ComponentType ct, AbstractComponentFunctor c)
        {
            LoadBodyItems(ct.componentInfo);

            IDictionary <string, Unit> units = new Dictionary <string, Unit>();

            int id_abstract = c.Id_abstract;

            // for each unit ...
            foreach (UnitType u in unit)
            {
                string uref = u.uRef;
                string iRef = u.iRef;
                //string urefSuper = u.super == null ? null : u.super.uRef;

                //   InterfaceDAO idao = new InterfaceDAO();
                Interface     i  = br.ufc.pargo.hpe.backend.DGAC.BackEnd.idao.retrieve(id_abstract, uref);
                InterfaceType ui = lookForInterface(iRef);

                foreach (SourceFileType sft in ui.sources[ui.sources.Length - 1].file)
                {
                    SourceCode ss = new SourceCode();
                    ss.Type_owner         = 'i';
                    ss.Id_owner_container = c.Id_abstract;
                    ss.Id_owner           = i.Id_interface;
                    ss.Contents           = sft.contents;
                    ss.File_type          = "dll";
                    ss.File_name          = sft.name;
                    br.ufc.pargo.hpe.backend.DGAC.BackEnd.scdao.update(ss);

                    if (sft.externalDependency != null)
                    {
                        foreach (string extRef in sft.externalDependency)
                        {
                            SourceCodeReference ssr = new SourceCodeReference();
                            ssr.Type_owner         = ss.Type_owner;
                            ssr.Id_owner_container = ss.Id_owner_container;
                            ssr.Id_owner           = ss.Id_owner;
                            ssr.File_name          = ss.File_name;
                            ssr.Reference          = extRef;
                            if (br.ufc.pargo.hpe.backend.DGAC.BackEnd.scrdao.retrieve(ssr) != null)
                            {
                                // DGAC.BackEnd.scrdao.update(ssr);
                            }
                            else
                            {
                                br.ufc.pargo.hpe.backend.DGAC.BackEnd.scrdao.insert(ssr);
                            }
                        }
                    }
                }
            }
        }
コード例 #49
0
        public void SkipWhitespaceTest()
        {
            SourceCode   source = new SourceCode("  \nclass");
            TokenFactory elems  = new TokenFactory(source);
            TokenWalker  walker = new TokenWalker(elems);

            walker.SkipWhitespace();
            Token current = walker.CurrentElement;

            Assert.AreEqual(current.Kind, SyntaxKeyword.Class);
            Assert.AreEqual(current.Context, new SourceContext(3, 5));
        }
コード例 #50
0
        public void InitializeCustumTypeVariable(RefType customType, string name)
        {
            if (!(customType is RefType type))
            {
                throw new ArgumentException($"{nameof(customType)} needs to be a reference type");
            }

            if (!DataTypes.Types[DataTypes.customTypes].Any(x => x.Name == customType.Name))
            {
                throw new InvalidOperationException($"{customType.Name} is in an array type.");
            }

            if (!Types.Any(x => x.Name == type.Name))
            {
                throw new InvalidOperationException($"{customType.Name} is not in the list of available types.");
            }

            if (Variables.Any(x => x.Name == name))
            {
                throw new InvalidOperationException($"Variable with name {name} already exists");
            }

            var variable = new Variable
            {
                Name  = name,
                Type  = customType,
                Value = NextAvailableHeap.ToString()
            };

            foreach (var property in customType.Properties)
            {
                var variableOnHeap = new Variable
                {
                    Name   = $"{name}.{property.Name}",
                    Type   = property.Type,
                    Value  = property.Type.Defaultvalue,
                    Parent = variable
                };

                variable.Variables.Add(variableOnHeap);

                Ram.SetVariable(NextAvailableHeap, variableOnHeap);
                NextAvailableHeap++;
            }

            Ram.SetVariable(NextAvailableStack, variable);

            Variables.Add(variable);

            NextAvailableStack++;

            SourceCode.Add($"{customType.Name} {name} = new {customType.Name}();");
        }
コード例 #51
0
 public SourceDocument ParseFile(SourceCode sourceCode, IEnumerable <Token> tokens, GlassScriptParserOptions options)
 {
     InitializeParser(sourceCode, tokens, options);
     try
     {
         return(ParseDocument());
     }
     catch (SyntaxException)
     {
         return(null);
     }
 }
コード例 #52
0
        public SourceDoc(SourceSpan span, SourceCode sourceCode, IEnumerable <SyntaxNode> children)
            : base(span)
        {
            SourceCode = sourceCode;
            Children   = children;

            /* Console.WriteLine($"{base.Display()}Source code");
             * foreach (var c in children)
             * {
             *   Console.WriteLine($"  {base.Display()}{c.Kind}");
             * }*/
        }
コード例 #53
0
    public SourceCode GetFileContents(string path, string name)
    {
        SourceCode sourceCode = new SourceCode();
        var        result     = File.ReadAllText(Path.Combine(basePath, path, name));

        if (result != null)
        {
            sourceCode.FileName      = name;
            sourceCode.sourceContent = result;
        }
        return(sourceCode);
    }
コード例 #54
0
        protected async override void OnAppearing()
        {
            #region AnimationsFadeIn
            await Task.WhenAll(
                CSharpDef.FadeTo(1, 500),
                definitions.FadeTo(1, 500),
                progLang.FadeTo(1, 500),
                OOP.FadeTo(1, 500),
                DotNETFramework.FadeTo(1, 500),
                clr.FadeTo(1, 500),
                cls.FadeTo(1, 500),
                cts.FadeTo(1, 500),
                MSIL.FadeTo(1, 500),
                JIT.FadeTo(1, 500),
                Compiler.FadeTo(1, 500),
                SourceCode.FadeTo(1, 500),
                ExecutableCode.FadeTo(1, 500),
                boxview1.FadeTo(1, 500),
                generalProgTerms.FadeTo(1, 500),
                Variables.FadeTo(1, 500),
                DataType.FadeTo(1, 500),
                Keywords.FadeTo(1, 500),
                Operators.FadeTo(1, 500),
                Expression.FadeTo(1, 500),
                TypeCasting.FadeTo(1, 500),
                Arrays.FadeTo(1, 500),
                Function.FadeTo(1, 500),
                Class.FadeTo(1, 500),
                Object.FadeTo(1, 500),
                Constructor.FadeTo(1, 500),
                Destructor.FadeTo(1, 500),
                Namespaces.FadeTo(1, 500),
                Exceptions.FadeTo(1, 500),
                ExceptionHandling.FadeTo(1, 500),
                boxview2.FadeTo(1, 500),
                oopProgTerms.FadeTo(1, 500),
                Inheritance.FadeTo(1, 500),
                BaseClass.FadeTo(1, 500),
                DerivedClass.FadeTo(1, 500),
                AbstractClass.FadeTo(1, 500),
                MultilevelInheritance.FadeTo(1, 500),
                HierarchicalInheritance.FadeTo(1, 500),
                SingleInheritance.FadeTo(1, 500),
                Interface.FadeTo(1, 500),
                Polymorphism.FadeTo(1, 500),
                Overriding.FadeTo(1, 500),
                Encapsulation.FadeTo(1, 500),
                Abstraction.FadeTo(1, 500),
                Overloading.FadeTo(1, 500));

            #endregion
        }
コード例 #55
0
ファイル: DataClass.cs プロジェクト: jingjing54007/mmo
        public SourceCode GenerateParseCode()
        {
            var code = new SourceCode();

            code.Append(GenerateParsePrototypeCode());
            code.BracketStart();
            {
                code.Append("if (root_node == nullptr) return;");
                code.BracketStart("for (TiXmlElement* each_node = root_node->FirstChildElement(); each_node != nullptr; each_node = each_node->NextSiblingElement())");
                {
                    code.Append("{0}* ptr = new {0};", QualifiedTypeName);

                    foreach (var field in Fields.Values)
                    {
                        code.Append(field.GenerateParseCode());
                    }

                    if (HasContent)
                    {
                        code.Append("ptr->{0} = std::string(each_node->GetText() != nullptr? each_node->GetText(): \"\");", IsNameContent ? "name" : "content");
                    }

                    code.NewLine();
                    if (IsTopMost)
                    {
                        code.Append("{0}_data::add(ptr);", SimpleName);
                    }
                    else
                    {
                        code.Append(HasId ? "parent->{0}.insert(std::make_pair(ptr->id, ptr));" : "parent->{0}.push_back(ptr);", CollectionName);
                    }

                    if (NeedLinker)
                    {
                        code.NewLine();
                    }

                    foreach (var field in ReferenceFields)
                    {
                        code.Append(field.GenerateParseRefCode());
                    }
                }
                code.BracketEnd();
            }
            code.BracketEnd();

            foreach (var field in DataClassFields)
            {
                code.Append(field.GenerateParseBodyCode());
            }
            return(code);
        }
コード例 #56
0
 public Expression ParseExpression(SourceCode sourceCode, IEnumerable <Token> tokens)
 {
     InitializeParser(sourceCode, tokens, GlassScriptParserOptions.OptionalSemicolons);
     try
     {
         return(ParseExpression());
     }
     catch (SyntaxException)
     {
         // Errors are located in the ErrorSink.
         return(null);
     }
 }
コード例 #57
0
        public void CalculateDiscount_TenDollarDiscountOn100DollarReturns10()
        {
            var sourceCode = new SourceCode
            {
                DiscountType      = DiscountType.PerOrder,
                DiscountValueType = DiscountValueType.Money,
                CouponValue       = 10m
            };

            var returnValue = sourceCode.CalculateDiscount(100m);

            Assert.AreEqual(10m, returnValue);
        }
コード例 #58
0
        //SourceCode ::= Statement+
        static public (SourceCode, string) parseSourceCode(ref lexer.Lexer Lexer)
        {
            SourceCode sourceCode = new SourceCode();
            string     error;

            sourceCode.LineNum             = Lexer.GetLineNum();
            (sourceCode.Statements, error) = parseStatements(ref Lexer);
            if (error != null)
            {
                return(sourceCode, error);
            }
            return(sourceCode, null);
        }
コード例 #59
0
 private void SetStack(IEnumerable <ExceptionStack> exceptionStack)
 {
     if (exceptionStack == null || exceptionStack.Count() == 0)
     {
         return;
     }
     foreach (var exception in exceptionStack)
     {
         string id    = exception.SourceCode;
         var    value = SourceCode.FromExceptionStack(exception);
         data.Add(id, value);
     }
 }
コード例 #60
0
        public SyntaxNode ParseStatement(SourceCode sourceCode, IEnumerable <Token> tokens, MonitorScriptParserOptions options)
        {
            InitializeParser(sourceCode, tokens, options);

            try
            {
                return(ParseStatement());
            }
            catch (SyntaxException)
            {
                return(null);
            }
        }