Example #1
0
        private void compilar()
        {
            this.setTextoAreaMensagem("");
            Lexico    lexico    = new Lexico(this.areaEditor.Text);
            Sintatico sintatico = new Sintatico();
            Semantico semantico = new Semantico();

            try
            {
                lexico.analisar();
                sintatico.analisar(lexico, semantico);
                this.setTextoAreaMensagem("programa compilado com sucesso");
            }
            catch (LexicalError e)
            {
                this.setTextoAreaMensagem(e.Message);
            }
            catch (SyntaticError e)
            {
                this.setTextoAreaMensagem(e.Message);
            }
            catch (SemanticError e)
            {
                this.setTextoAreaMensagem(string.Format("Erro: {0}", e.Message));
            }
        }
Example #2
0
        public void CanUseConcreteTypeForUserObject()
        {
            var myUserObject = 3.14f;
            var obj          = Lexico.Parse <ClassWithConcreteUserObject>("5", userObject: myUserObject);

            Assert.Equal(myUserObject, obj.UserObject);
        }
Example #3
0
        public void CanRetrieveUserObject()
        {
            var myUserObject = new object();
            var obj          = Lexico.Parse <ClassWithUserObject>("5", userObject: myUserObject);

            Assert.Equal(myUserObject, obj.UserObject);
        }
Example #4
0
        public void CanRetrieveUserObjectValueType()
        {
            var myUserObject = 3.14f;
            var obj          = Lexico.Parse <ClassWithUserObject>("5", userObject: myUserObject);

            Assert.Equal(myUserObject, obj.UserObject);
        }
Example #5
0
    public static void Main(String[] args)
    {
        SCG.IComparer <Rec <string, int> > lexico1 = new Lexico();
        SCG.IComparer <Rec <string, int> > lexico2 =
            new DelegateComparer <Rec <string, int> >(
                delegate(Rec <string, int> item1, Rec <string, int> item2) {
            int major = item1.X1.CompareTo(item2.X1);
            return(major != 0 ? major : item1.X2.CompareTo(item2.X2));
        });
        Rec <String, int> r1 = new Rec <String, int>("Carsten", 1962);
        Rec <String, int> r2 = new Rec <String, int>("Carsten", 1964);
        Rec <String, int> r3 = new Rec <String, int>("Christian", 1932);

        Console.WriteLine(lexico1.Compare(r1, r1) == 0);
        Console.WriteLine(lexico1.Compare(r1, r2) < 0);
        Console.WriteLine(lexico1.Compare(r2, r3) < 0);
        Console.WriteLine(lexico2.Compare(r1, r1) == 0);
        Console.WriteLine(lexico2.Compare(r1, r2) < 0);
        Console.WriteLine(lexico2.Compare(r2, r3) < 0);

        SCG.IComparer <String> rev
            = ReverseComparer <String>(Comparer <String> .Default);
        Console.WriteLine(rev.Compare("A", "A") == 0);
        Console.WriteLine(rev.Compare("A", "B") > 0);
        Console.WriteLine(rev.Compare("B", "A") < 0);
    }
Example #6
0
        public void executa(string comandos)
        {
            try
            {
                tabResultado.SelectedIndex = 0;
                clearMensagem();
                Stopwatch sw = new Stopwatch();
                sw.Start();
                addMensagem("Executando...");
                Semantico semantico = new Semantico(this);
                Lexico    lexico    = new Lexico(comandos);
                Sintatico sintatico = new Sintatico();
                sintatico.parse(lexico, semantico);
                semantico.Dispose();
                semantico = null;
                sw.Stop();

                Base.getInstance().commit();

                TimeSpan tempo = sw.Elapsed;
                addMensagem(String.Format("Sucesso!!! Tempo de Execução: {0}min {1}s {2}ms", tempo.Minutes, tempo.Seconds, tempo.Milliseconds));
            }
            catch (Exception ex)
            {
                addMensagem("#ERROR: " + ex.ToString());
                //Console.WriteLine(ex.StackTrace);
            }
        }
Example #7
0
        private TestTrace <TParserToCheck> TestParse <TTopParser, TParserToCheck>(string parseString)
        {
            var rtn    = new TestTrace <TParserToCheck>();
            var result = Lexico.Parse <TTopParser>(parseString, rtn);

            return(rtn);
        }
Example #8
0
        public void LexicoJsonWithNoOpTrace()
        {
            var result = Lexico.Parse <JsonDocument>(JsonString, new NoTrace());

            if (result.value == null)
            {
                throw new Exception("Parsing failed");
            }
        }
Example #9
0
        private void ProcessarPrograma(Lexico lexico)
        {
            Token t = lexico.NextToken();

            while (t != null)
            {
                t = lexico.NextToken();
            }
        }
Example #10
0
 public void IndirectAlternative(Type parseType, string expression, bool passes)
 {
     if (passes)
     {
         Assert.True(Lexico.TryParse(expression, parseType, out _, new ConsoleDeveloperTrace()));
     }
     else
     {
         Assert.False(Lexico.TryParse(expression, parseType, out _, new ConsoleDeveloperTrace()));
     }
 }
Example #11
0
 public void ExplicitAlternative(string expression, bool passes)
 {
     if (passes)
     {
         Assert.True(Lexico.TryParse(expression, out Truthy _, new ConsoleDeveloperTrace()));
     }
     else
     {
         Assert.False(Lexico.TryParse(expression, out Truthy _, new ConsoleDeveloperTrace()));
     }
 }
Example #12
0
        private void compilar()
        {
            if (arquivo == "")
            {
                salvarArquivo();
            }

            richTextBox2.Clear();
            Lexico    lexico    = new Lexico();
            Sintatico sintatico = new Sintatico();
            Semantico semantico = null;

            semantico = Semantico.GetInstance();

            lexico.setInput(richTextBox1.Text);
            string arq = Path.GetFileNameWithoutExtension(statusStrip1.Items[1].ToString());

            semantico.NomeArq = arq;
            try
            {
                sintatico.parse(lexico, semantico);
                richTextBox2.AppendText("programa compilado com sucesso");
                this.compilado = true;
                Token t = null;

                /*  richTextBox2.AppendText("linha\t\tclasse\t\t\tlexema"+Environment.NewLine);
                 * while ( (t = lexico.nextToken()) != null )
                 * {
                 *    richTextBox2.AppendText(t.Position + "\t\t"+ t.getTipoToken() +"\t\t" +t.Lexeme +Environment.NewLine);
                 *
                 * }*/
            }
            catch (LexicalError e)
            {
                richTextBox2.Clear();
                richTextBox2.AppendText(" Erro na linha " + e.getPosition() + " - " + e.Message + Environment.NewLine);
            }
            catch (SyntaticError e)
            {
                richTextBox2.Clear();
                richTextBox2.AppendText(" Erro na linha " + e.getPosition() + " - " + e.Message + Environment.NewLine);
            }
            catch (SemanticError e)
            {
                richTextBox2.Clear();
                richTextBox2.AppendText(" Erro na linha " + e.getPosition() + " - " + e.Message + Environment.NewLine);
            }
            catch (Exception e)
            {
                richTextBox2.Clear();
                richTextBox2.AppendText(" Erro não tratado/previsto:  - " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }
Example #13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void parse(Lexico scanner, Semantico semanticAnalyser) throws LexicalError, SyntaticError, SemanticError
    public virtual void parse(Lexico scanner, Semantico semanticAnalyser)
    {
        this.scanner          = scanner;
        this.semanticAnalyser = semanticAnalyser;

        stack.Clear();
        stack.Push(new int?(Constants_Fields.DOLLAR));
        stack.Push(new int?(ParserConstants_Fields.START_SYMBOL));

        currentToken = scanner.nextToken();

        while (!step())
        {
            ;
        }
    }
Example #14
0
    public void parse(Lexico scanner, Semantico semanticAnalyser)
    {
        this.scanner          = scanner;
        this.semanticAnalyser = semanticAnalyser;

        stack.Clear();
        stack.Push(DOLLAR);
        stack.Push((parserConst.START_SYMBOL));

        currentToken = scanner.nextToken();

        while (!step())
        {
            ;
        }
    }
Example #15
0
        private void analizarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            salida.Text = "";
            seleccion.Items.Clear();
            documentos.Items.Clear();

            img.Image = null;

            TabPage     n = entrada.SelectedTab;
            RichTextBox t = (RichTextBox)n.Controls[0];

            if (t.Text != "")
            {
                Lexico temp = new Lexico(t.Text, salida, seleccion, documentos);
                temp.Analizar();
            }
        }
Example #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            scanner = new Lexico();
            if (txtInput.Text.Length != 0)
            {
                scanner.autamataFinitoDeterministico(txtInput.Text);
                if (!scanner.tablaErrores.Any())
                {
                    Console.WriteLine("No hay errores");
                }
                else
                    Console.WriteLine("Exiten errores");



            }
            else
                Console.WriteLine("No hay nada para analizar");
        }
Example #17
0
        public bool Compile(string programa)
        {
            Sintatico sintatico = new Sintatico();

            programa = programa.Trim();

            if (string.IsNullOrWhiteSpace(programa))
            {
                return(false);
            }

            try
            {
                Lexico    lexico    = new Lexico(programa);
                Semantico semantico = new Semantico();

                sintatico.Parse(lexico, semantico);

                ProcessarPrograma(lexico);

                Assembly = string.Join(Environment.NewLine, semantico.Codigo);

                return(true);
            }
            catch (LexicalException ex)
            {
                throw new LexicalException(string.Format("Erro na linha {0}: {1}", GetLine(programa, ex.Position), ex.Message));
            }
            catch (SyntaticException ex)
            {
                throw new SyntaticException(string.Format("Erro na linha {0}: encontrado {1} esperado {2}", GetLine(programa, ex.Position), sintatico.CurrentToken.Lexeme, ex.Message));
            }
            catch (SemanticException ex)
            {
                throw new SemanticException(string.Format("Erro na linha {0}: {1}", GetLine(programa, ex.Position), ex.Message));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Erro desconhecido: {0} {1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace));
            }
        }
Example #18
0
        private void BtnCompilar_Click(object sender, RoutedEventArgs e)
        {
            var sourceCode = new TextRange(CodigoFonte.Document.ContentStart, CodigoFonte.Document.ContentEnd).Text;

            if (sourceCode == "" || sourceCode == "\r\n")
            {
                MessageBox.Show("Não há nada para ser compilado!\nPor favor digite um código fonte.", "Atenção!", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            Lexico.ScanText(sourceCode);
            if (Lexico.ContemErroLexico)
            {
                var erros = Lexico.Tokens.Where(t => t.Tag == SimpleCompilerService.Suporte.Tag.ERRO_LEXICO).ToList();
                Console.Text = ErroLexico(erros);
            }
            else
            {
                try
                {
                    Sintatico.Analyze();

                    var sucesso = "Análise Léxica ✓\r\nAnálise Sintática ✓\r\nAnálise Semântica ✓\r\n\r\nHora: " + DateTime.Now.ToLongTimeString();
                    Console.Text = sucesso;
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("#sintatico#"))
                    {
                        Console.Text = ErroSintatico(ex.Message);
                    }
                    else
                    {
                        Console.Text = ErroSemantico(ex.Message);
                    }
                }
            }
        }
        static int Main(string[] args)
        {
            /*
             * if (args.Length == 0) {
             *  Console.WriteLine("Digite o nome do arquivo de entrada!");
             *  return 1;
             * }*/

            //var path = System.IO.Path.Combine(Environment.CurrentDirectory, args[0]);
            var path = "Teste.c";

            if (System.IO.File.Exists(path))
            {
                io = new ModuloIO(path);
                analisadorLexico = new Lexico();
                analisadorLexico.Executa(io);
                io.SalvaTokens(analisadorLexico.ListaTokens);
                foreach (Token tk in analisadorLexico.ListaTokens)
                {
                    Console.WriteLine(tk.ToString());
                }

                if (analisadorLexico.Status)
                {
                    analisadorSintatico = new Sintatico(analisadorLexico.ListaTokens);
                    analisadorSintatico.Programa();
                    Debuga();
                }

                return(0);
            }
            else
            {
                Console.WriteLine("Arquivo não existe!");
                return(1);
            }
        }
Example #20
0
 public void WritePrivateSetProperty() => Assert.Equal(5, Lexico.Parse <GetOnlyPropWithPrivateSet>("5").Value);
Example #21
0
 public void CannotWriteGetOnlyProperty() => Assert.NotEqual(5, Lexico.Parse <GetOnlyProp>("5").Value);
Example #22
0
 public void EmptyUserTraceDoesntBlowUp()
 {
     var result = Lexico.TryParse("5", out int i, new UserTrace(Console.WriteLine));
 }
Example #23
0
 public void SeperatorWithinRepeatedRecursive() => Lexico.Parse <List <RecBase> >("foobar,bar")
 .Should()
 .ContainEquivalentOf(new Recursive {
     RecBase = { new LiteralCase(), new LiteralCase() }
 });
Example #24
0
 public Parser(Lexico.Lexico lexer)
 {
     lex = lexer;
     currentToken = lex.NextToken();
 }
Example #25
0
 public void OrderOfGenericSequenceCorrect() => Lexico.Parse <GenericWrapper>(" 5 ", new ConsoleDeveloperTrace());
Example #26
0
 public void OrderOfSequenceCorrect()
 {
     Assert.True(Lexico.TryParse(" 5 ", out NonGenericSequence _, new ConsoleDeveloperTrace()));
 }
Example #27
0
                                                                                                    regexPattern, config, flags);  // TODO: Don't pass in regexPattern, retrieve it by unparsing

        public static IParser Parse(string pattern, IConfig config, ParserFlags flags) => Lexico.Parse <Regex>(pattern).Create(pattern, config, flags);
Example #28
0
 public void BadExplicitAlternativeType()
 {
     Assert.Throws <ArgumentException>(() => Lexico.Parse <TruthyWithInvalidAlternative>("true", new ConsoleDeveloperTrace()));
 }
Example #29
0
 public void CannotWriteReadonlyField() => Assert.NotEqual(5, Lexico.Parse <ReadonlyField>("5").Value);
Example #30
0
 public cParser(Lexico.Lexico lexer)
     : base(lexer)
 {
 }
Example #31
0
 public parserC(Lexico.Lexico lexer)
     : base(lexer)
 {
 }
Example #32
0
 public void WriteProtectedField() => Assert.Equal(5, Lexico.Parse <ProtectedField>("5").Val);
Example #33
0
        public void WrongUserObjectTypeThrowsCastException()
        {
            var myUserObject = 3;

            Assert.Throws <InvalidCastException>(() => Lexico.Parse <ClassWithConcreteUserObject>("5", userObject: myUserObject));
        }