Beispiel #1
0
 void ApplyRule(Rule rule, AbstractSyntaxTree suppliedArguments = null)
 {
     if (ArgsCheck(rule, suppliedArguments))
     {
         if (rule.Condition == null || AsBoolean(EvalCode(rule.Condition)))
         {
             if (RulesDebuggingCommand > 0)
             {
                 Console.WriteLine("[Rule " + rule.Atom + " applies.]");
             }
             if (rule.Code != null)
             {
                 ExecuteStatement(rule.Code);
             }
         }
         else if (RulesDebuggingCommand >= 2)
         {
             Console.WriteLine("[Rule " + rule.Atom + " does NOT apply.]");
         }
     }
     else if (RulesDebuggingCommand >= 2)
     {
         Console.WriteLine("[Rule " + rule.Atom + " does NOT apply.]");
     }
 }
Beispiel #2
0
    // all parameters should be bound to arguments, but the relation-name needn't actually exist
    AbstractSyntaxTree TestRelation(AbstractSyntaxTree node)
    {
        if (node.ValueType != ValueTypes.code)
        {
            return(node);
        }
        string relationToFind = node.ToString();

        if (relationToFind == FillInThisBlank)
        {
            return(node);
        }
        Rule rule = null;

        if (relationToFind.Contains(FillInThisBlank))
        {
            var pieces = relationToFind.Split(new[] { FillInThisBlank[0] }, StringSplitOptions.RemoveEmptyEntries);
            if (pieces.Length > 2)
            {
                throw new Exception("Can't have two " + FillInThisBlank + " placeholders in " + relationToFind);                                // todo remove this restriction
            }
            rule = AllRules.Find(r => r.Atom.StartsWith(pieces[0]) && r.Atom.EndsWith(pieces[1]));
        }
        else
        {
            rule = AllRules.Find(r => r.Atom == relationToFind);
        }
        return((rule != null) ? rule.Code ?? Yes : No);
    }
 public void SetUp()
 {
     lexerMock       = new Mock <ILexer>();
     ast             = new AbstractSyntaxTree();
     symbolTableMock = new Mock <ISymbolTable>();
     loggerMock      = new Mock <ILogger <SyntaxAnalyser> >();
 }
Beispiel #4
0
        public SemanticAnalyzer(
            List <ZenFileNode> zenFileNodes,
            List <IParseTree> parseTrees,
            List <string> filesPaths,
            List <string[]> filesContents,
            List <HashSet <string> > suppressedWarningCodes
            )
        {
            DaedalusParseTreeVisitor visitor = new DaedalusParseTreeVisitor();

            _zenFileNodes           = zenFileNodes;
            SymbolTable             = null;
            SymbolsWithInstructions = null;

            AbstractSyntaxTree = new AbstractSyntaxTree(filesPaths, filesContents, suppressedWarningCodes);

            int index = 0;

            foreach (IParseTree parseTree in parseTrees)
            {
                ((ICommonDaedalusParseTreeVisitor)visitor).Reset(index);
                AbstractSyntaxTree.Extend(parseTree, visitor, index);
                index++;
            }
        }
        public static TypeStatement Identify(
            string typeIdentifier,
            ClassMetadata classMetadata,
            AbstractSyntaxTree ast,
            TypeOverrideDetails typeOverrideDetails
            )
        {
            // Get node from typeIdentifier
            var node = ast.RootNode.OfKind(
                SyntaxKind.TypeAliasDeclaration
                ).FirstOrDefault(
                child => child.IdentifierStr == typeIdentifier
                );

            if (node == null)
            {
                return(null);
            }

            return(GenericTypeIdentifier.Identify(
                       node.Last,
                       classMetadata,
                       ast,
                       typeOverrideDetails
                       ));
        }
Beispiel #6
0
        public static SemanticModel Transform(AbstractSyntaxTree ast)
        {
            var transformations = new[] { new ApplyDefaults() };
            var transformedAst  = transformations.Aggregate(ast, (a, t) => t.Transform(a));

            return(new SemanticModel(transformedAst));
        }
Beispiel #7
0
 private static IList <TypeStatement> GetGenericTypes(
     Node node,
     ClassMetadata classMetadata,
     AbstractSyntaxTree ast,
     TypeOverrideDetails typeOverrideDetails
     )
 {
     if (node.Kind == SyntaxKind.ClassDeclaration &&
         node.TypeParameters != null
         )
     {
         return(node.TypeParameters.Select(
                    typeParam => GenericTypeIdentifier.Identify(
                        typeParam,
                        classMetadata,
                        ast,
                        typeOverrideDetails
                        )
                    ).ToList());
     }
     else if (node.Kind == SyntaxKind.InterfaceDeclaration &&
              node.TypeParameters != null
              )
     {
         return(node.TypeParameters.Select(
                    typeParam => GenericTypeIdentifier.Identify(
                        typeParam,
                        classMetadata,
                        ast,
                        typeOverrideDetails
                        )
                    ).ToList());
     }
     return(new List <TypeStatement>());
 }
Beispiel #8
0
    AbstractSyntaxTree CloneTreeWithParamsBoundToArgs(AbstractSyntaxTree node, out bool allBound)
    {
        var retval = new AbstractSyntaxTree(node);

        allBound = true;
        for (var subnode = retval.Right; subnode != null; subnode = subnode.Right)
        {
            var paramNode = (subnode.Value == ",") ? subnode.Left : subnode;
            if (paramNode.Value == FillInThisBlank)
            {
                if (!allBound)
                {
                    throw new Exception("Can't have two " + FillInThisBlank + " placeholders in " + node);
                }
                allBound = false;
            }
            else if (paramNode.ValueType == ValueTypes.code)             // values are already simply copied
            {
                var parameter = AllRules.FirstOrDefault(r => r.Atom == paramNode.Value);
                if (parameter != null && parameter.Code != null)
                {
                    paramNode.Value = EvalCode(parameter.Code).ToString();
                }
            }
        }
        return(retval);
    }
Beispiel #9
0
 private bool IsNextNodeElse(string markerJumpPrevBody, string markerJumpAfterBody)
 {
     if (parent == null)
     {
         ASTNode node = AbstractSyntaxTree.GetParentNode(this);
         if (node != null)
         {
             ASTNode nodeNext = (node as IArea).GetNextNode(parent);
             if (nodeNext != null && nodeNext is ElseAST nodeNextElseAST)
             {
                 if (markerJumpPrevBody == "")
                 {
                     markerJumpPrevBody = ASMregisters.GetNewMarkerJumpPrevBody();
                 }
                 nodeNextElseAST.SetMarkersJump(markerJumpPrevBody, markerJumpAfterBody);
                 return(true);
             }
         }
     }
     else
     {
         ASTNode nodeNext = (parent.parent as IArea).GetNextNode(parent);
         if (nodeNext != null && nodeNext is ElseAST nodeNextElseAST)
         {
             if (markerJumpPrevBody == "")
             {
                 markerJumpPrevBody = ASMregisters.GetNewMarkerJumpPrevBody();
             }
             nodeNextElseAST.SetMarkersJump(markerJumpPrevBody, markerJumpAfterBody);
             return(true);
         }
     }
     return(false);
 }
        public override void Transform(AbstractSyntaxTree astNode)
        {
            bool isFor = astNode.Type == TokenType.ForLoop && !astNode.Children.Any(child => child.Type == TokenType.In);

            if (!isFor)
            {
                return;
            }

            //init
            if (astNode.Children[2].Type == TokenType.EndOfLine)
            {
                astNode.Children.Insert(2, new AbstractSyntaxTree(new Node(TokenType.Empty), new List <AbstractSyntaxTree>()));
            }

            //condition
            if (astNode.Children[4].Type == TokenType.EndOfLine)
            {
                astNode.Children.Insert(4, new AbstractSyntaxTree(new Node(TokenType.Empty), new List <AbstractSyntaxTree>()));
            }

            //increment
            if (astNode.Children[6].Type == TokenType.RightParenthesis)
            {
                astNode.Children.Insert(6, new AbstractSyntaxTree(new Node(TokenType.Empty), new List <AbstractSyntaxTree>()));
            }
        }
Beispiel #11
0
        public static TypeQueryStatement Identify(
            Node node,
            ClassMetadata classMetadata,
            AbstractSyntaxTree ast,
            TypeOverrideDetails typeOverrideDetails
            )
        {
            if (node.Kind != GenerationIdentifiedTypes.TypeQuery ||
                node.First?.First == null)
            {
                return(null);
            }
            var firstNode = node.First;

            return(new TypeQueryStatement
            {
                Class = TypeIdentifier.Identify(
                    firstNode.First,
                    classMetadata
                    ),
                Type = TypeIdentifier.Identify(
                    firstNode.Last,
                    classMetadata
                    )
            });
        }
 public override bool Identify(
     string identifierString,
     AbstractSyntaxTree ast
     )
 {
     if (!_isCachedSetup)
     {
         var classDeclarations = ast.RootNode.OfKind(
             SyntaxKind.ClassDeclaration
             );
         foreach (var classDeclaration in classDeclarations)
         {
             _cacheClassDeclaration.Add(classDeclaration.IdentifierStr);
         }
         var interfaceDeclarations = ast.RootNode.OfKind(
             SyntaxKind.InterfaceDeclaration
             );
         foreach (var interfaceDeclaration in interfaceDeclarations)
         {
             _cacheInterfaceDeclaration.Add(interfaceDeclaration.IdentifierStr);
         }
         _isCachedSetup = true;
     }
     return(!_cacheClassDeclaration.Contains(identifierString) &&
            _cacheInterfaceDeclaration.Contains(identifierString));
 }
Beispiel #13
0
    public static AbstractSyntaxTree AppendOperand(this AbstractSyntaxTree root, string operandValue, ValueTypes vt = ValueTypes.code)
    {
        decimal d;
        bool    bResult;

        if (decimal.TryParse(operandValue, out d))
        {
            vt = ValueTypes.number;
        }
        else if (bool.TryParse(operandValue, out bResult))
        {
            vt = ValueTypes.boolean;
        }
        else if (operandValue.StartsWith("\"") && operandValue.EndsWith("\""))
        {
            vt           = ValueTypes.text;
            operandValue = operandValue.Substring(1, operandValue.Length - 2);
        }
        if (root == null)
        {
            return(new AbstractSyntaxTree(operandValue, vt));
        }
        var current = root;

        while (current.Right != null)
        {
            current = current.Right;
        }
        current.Right = new AbstractSyntaxTree(operandValue, vt);
        return(root);
    }
Beispiel #14
0
        /// <summary>
        /// Get the known types from the <see cref="AbstractSyntaxTree"/>.
        /// </summary>
        /// <param name="abstractSyntaxTree"></param>
        /// <returns></returns>
        public static List <KnownType> GetKnownTypes(AbstractSyntaxTree abstractSyntaxTree)
        {
            var harvester = new KnownTypesHarvester();

            harvester.Visit(abstractSyntaxTree);
            return(harvester._knownTypes);
        }
        public override void Transform(AbstractSyntaxTree astNode)
        {
            if (astNode.Type == TokenType.FullSymbol)
            {
                if (astNode.Children.Count == 1)
                {
                    return;
                }
                else
                {
                    var old   = astNode.Children;
                    int count = old.Count;

                    var head = old.Take(count - 2);
                    var dot  = old[count - 2];
                    var tail = old[count - 1];

                    var headNode = head.Count() > 1 ? new AbstractSyntaxTree(new Node(TokenType.FullSymbol), head.ToList()) : head.First();

                    astNode.Children = new List <AbstractSyntaxTree>()
                    {
                        headNode, tail, dot
                    };
                }
            }
        }
Beispiel #16
0
    bool AsBoolean(AbstractSyntaxTree node)
    {
        bool retval = false;

        if (bool.TryParse(node.Value, out retval))
        {
            return(retval);
        }
        if (node.ValueType == ValueTypes.number)
        {
            return(true);                                             // a non-void rule was found
        }
        if (node.ValueType == ValueTypes.text)
        {
            return(true);
        }
        if (node.ValueType == ValueTypes.code && node.IsOperand)
        {
            return(true);
        }
        if (node.ValueType == ValueTypes.code && node.Value == "(")
        {
            foreach (var item in ForEach_(node))
            {
                return(true);
            }
        }
        return(false);
    }
Beispiel #17
0
 public virtual void Apply(AbstractSyntaxTree tree)
 {
     tree.Children.ForEach(t =>
     {
         Transform(t);
         Apply(t);
     });
 }
Beispiel #18
0
 private static void PrintAst(AbstractSyntaxTree ast)
 {
     foreach (GameObjectNode gameObject in ast.Root.GameObjects.Values)
     {
         AstPrinter astPrinter = new AstPrinter();
         astPrinter.Visit(gameObject);
     }
 }
Beispiel #19
0
 private AbstractSyntaxTree SimplifyTree(AbstractSyntaxTree tree)
 {
     for (int i = 0; i < tree.Nodes.Count; i++)
     {
         tree.Nodes[i] = CorrectTree(tree.Nodes[i]);
     }
     return(tree);
 }
Beispiel #20
0
 public string PrettyPrint(AbstractSyntaxTree tree)
 {
     for (int i = 0; i < tree.Nodes.Count; i++)
     {
         RecursePrint(tree.Nodes[i]);
     }
     return(builder.ToString());
 }
Beispiel #21
0
 public override void PrintASM(string leveltabulation, bool isNewLine = false)
 {
     if (parent == null)
     {
         AbstractSyntaxTree.GetParentNode(this);
     }
     SetJumpMark(leveltabulation, parent);
 }
 public override void Apply(AbstractSyntaxTree tree)
 {
     tree.Children.ForEach(t =>
     {
         Apply(t);
         Transform(t);
     });
 }
Beispiel #23
0
 public void TypeCheck_Visit_AddNullFunctionInvocationToInteger()
 {
     Assert.Throws <Exception>(() =>
     {
         AbstractSyntaxTree ast = TestAstBuilder.BuildAst(TestCode6);
         TestDelegate(ast);
     });
 }
        private EvaluationResult EvaluateExpression(AbstractSyntaxTree tree, IEnumerable <IGlobalMethodProvider> providers)
        {
            var context = new EvaluationContext {
                Tree = tree,
                MethodInvocationCallback = (m, args) => Evaluate(providers, m, args)
            };

            return(new Interpreter().Evalutate(context));
        }
Beispiel #25
0
        public void TypeCheck_Visit_MemberAccessNotFoundIfNotDeclared()
        {
            Assert.Throws <Exception>(() =>
            {
                AbstractSyntaxTree ast = TestAstBuilder.BuildAst(TestCode3);

                TestDelegate(ast);
            });
        }
Beispiel #26
0
 public AbstractSyntaxTree(string operandValue, ValueTypes vt = ValueTypes.code)
 {
     //if (operandValue == null)
     //	throw new ArgumentNullException("operandValue");
     Value      = operandValue;
     Left       = Right = null;
     Precedence = int.MaxValue;
     ValueType  = vt;
 }
Beispiel #27
0
        public void TypeCheck_Visit_ArrayPlusIntegerFails()
        {
            Assert.Throws <Exception>(() =>
            {
                AbstractSyntaxTree ast = TestAstBuilder.BuildAst(TestCode2);

                TestDelegate(ast);
            });
        }
 public new Dictionary <string, Symbol> VisitTree(AbstractSyntaxTree tree)
 {
     base.VisitTree(tree);
     if (_nestedAttributesFound)
     {
         _symbolTable[HELPER_INSTANCE] = _helperInstance;
     }
     return(_symbolTable);
 }
Beispiel #29
0
 public void LinkChecker_Visit_InValidMemberAccessThrows()
 {
     Assert.Throws <Exception>(() =>
     {
         AbstractSyntaxTree ast  = TestAstBuilder.BuildAst(TestCode3_3, TestCode3_2);
         LinkChecker linkChecker = new LinkChecker(ast);
         linkChecker.Visit(ast.Root.GameObjects["SampleScreen1"]);
     });
 }
Beispiel #30
0
        public void LinkChecker_Visit_ThrowOnInvalidExitLink()
        {
            AbstractSyntaxTree ast         = TestAstBuilder.BuildAst(TestCode1_1, TestCode1_2);
            LinkChecker        linkChecker = new LinkChecker(ast);

            void TestDelegate() => linkChecker.Visit(ast.Root.GameObjects["SampleScreen1"]);

            Assert.Throws <Exception>(TestDelegate);
        }