Is it feasible to use Antlr for source code completion? - antlr

I don't know, if this question is valid since i'm not very familiar with source code parsing. My goal is to write a source code completion function for one existing programming language (Language "X") for learning purposes.
Is Antlr(v4) suitable for such a task or should the necessary AST/Parse Tree creation and parsing be done by hand, assuming no existing solutions exists?
I haven't found much information about that specific topic, except a list of compiler books, except a compiler is not what i'm after for.

The code completion in GoWorks is completely implemented using ANTLR 4. The following video shows the level of completion of this code completion engine. The code completion example runs from 5 minutes through the end of the video.
Intro to Tunnel Vision Labs' GoWorks IDE (Preview Release)
I have been working on code completion algorithms for many years, and strongly believe that there is no better solution (automated or manual) for producing a code completion solution for a new language that meets the requirements for what I would call highly-responsive code completion. If you are not interested in that level of performance or accuracy, other solutions may be easier for you to get involved with (I don't work with those personally, because I am too easily disappointed in the results).

Xtext uses ANTLR3 and has good autocomplete facilities. The problem is, it generates a seperate parser (again using antlr3) for autocomplete processing which is derived from AbstractInternalContentAssistParser. This multi-thousand line code part shows that the error recovery of ANTLR3 alone found to be insufficient by the xtext team.
Meanwhile ANTLR4 has a function parser.getExpectedTokensWithinCurrentRule() which lists possible token types for given position. It works when used in a ParseTreeListener. Remaining is semantics, scoping etc which is out of ANTLRs scope.

Related

Using ANTLR4 lexing for Code Completion in Netbeans Platform

I am using ANTLR4 to parse code in my Netbeans Platform application. I have successfully implemented syntax highlighting using ANTLR4 and Netbeans mechanisms.
I have also implemented a simple code completion for two of my tokens. At the moment I am using a simple implementation from a tutorial, which searches for a whitespace and starts the completion process from there. This works, but it deems the user to prefix a whitespace before starting code completion.
My question: is it possible or even contemplated using ANTLR's lexer to determine which tokens are currently read from the input to determine the correct completion item?
I would appreciate every pointer in the right direction to improve this behaviour.
not really an answer, but I do not have enough reputation points to post comments.
is it possible or even contemplated using ANTLR's lexer to determine which tokens are currently read from the input to determine the correct completion item?
Have a look here: http://www.antlr3.org/pipermail/antlr-interest/2008-November/031576.html
and here: https://groups.google.com/forum/#!topic/antlr-discussion/DbJ-2qBmNk0
Bear in mind that first post was written in 2008 and current antlr v4 is very different from the one available at the time, which is why Sam’s opinion on this topic appear to have evolved.
My personal experience - most of what you are asking is probably doable with antlr, but you would have to know antlr very well. A more straightforward option is to use antlr to gather information about the context and use your own heuristics to decide what needs to be shown in this context.
The ANTLRv3 grammar https://sourceware.org/git/?p=frysk.git;a=blob_plain;f=frysk-core/frysk/expr/CExpr.g;hb=HEAD implements context sensitive completion of C expressions (no macros).
For instance, if fed the string:
a_struct->a<tab>
it would just lists the fields of "a_struct" starting with "a" (tab could, technically be any character or marker).
The technique it used was to:
modify a C grammar to recognize both IDENT and IDENT_TAB tokens
for IDENT_TAB capture the partial expression AST and "TOKEN_TAB" and throw them back to 'main' (there are hacks to help capture the AST)
'main' then performs a type-eval on the partial expression (compute the expression's type not value) and use that to expand TOKEN_TAB
the same technique, while not exactly ideal, can certainly be used in ANTLRv4.

How would you effectively test command line software, with many switches and arguments

A command line utility/software could potentially consist of many different switches and arguments.
Lets say your software is called CLI and lets say CLI has the following features:
The general syntax of CLI is:
CLI <data structures> <operation> <required arguments> [optional arguments]
<data structures> could be 'matrix', 'complex numbers', 'int', 'floating point', 'log'
<operation> could be 'add', 'subtract', 'multiply', 'divide'
I cant think of any required and optional arguments, but lets say your software does support it
Now you want to test this software. And you wish to test interface itself, not the logic. Essentially the interface must return the correct success codes and error codes.
Essentially a lot of real word software still present a Command Line interface with several options. I am curious if there is any formal testing methodology established for this. One idea i had was to construct a grammar (like EBNF) and describing the 'language' of the interface. But I fail to push this idea ahead. What good is a grammar for in this case? How does it enable the generation of many many combinations .
I am curious to learn more about any theoretical models which could be applied to such a problem or if anyone in here has actually done such testing with satisfying coverage
There is a command-line tool as part of a product i maintain, and i have a situation thats very similar to what you describe. What i did was employ a unit testing framework, and encode each combination of arguments as a test method.
The program is implemented in c#/.NET, so i use microsoft's testing framework that's builtin to Visual Studio, but the approach would work with any unit testing framework.
Each test invokes a utility function that starts the process and sends in the input and cole ts the output. Then, each test is responsible for verifying that the output from the CLI matches what was expected. In some cases, there's a family of test cases that can be performed by a single test method, wih a for loop in it. The logic needs to run the CLI and check the output for each iteration.
The set of tests i have does not cover every permutation of arguments, but it covers the 80% cases and i can add new tests if there are ever any defects.
Using a recursive grammar to generate switches is an interesting idea. If you where to try this then you would need to first write the grammar in such a way that all switches could be used, and then do a random walk of the grammar.
This provides an easy method of randomly walking a grammar and outputting the result.

How to encourage positive developer behavior with an IDE?

The goal of IDEs is increase productivity. They do a great job at that. Refactoring, navigation, inline documentation, auto completion help increase productivity immensely.
But: Every tool is a weapon. The very same IDE helps to produce chunk code. Some IDE features are an invitation to produce bad code: code generation, code formatting tools, refactoring tools.
IDE overuse tends to isolate developers from the necessary details. It is a good thing that you can start working but at some point in your career you have to be able to figure out how to start a process. You can ignore this detail for some time, in the end they are important to write a working product (vs. bolted together stuff that works 90% of the time).
How do you encourage positive behavior of other developers working with an IDE? This is a question as old as copy and paste.
To get the right impression: developers have to have the maximum freedom to mobilize their maximum creativity and motivation. They may use IDEs and all the related tools as they see fit. Nobody should impose draconian measures on them. I don't want to demotivate and force someone to do something. Good behavior has to be encouraged. It has to itch little a bit if you do the wrong thing. In the same line as the SO "accept rate" metric (and reputation). You can ignore it but life is better if you follow the rules.
(The solution should work in a given setting. You can ignore reviews, changing the staffing or more education as potential solutions.)
Train your IDE, instead of being trained by it.
Set up code formatting the way you (or your team) wants it. Heck, even disable it in cases where it makes sense. I've never seen an IDE align something like this with a sensible combination of tabs and spaces (where \t is obviously the tab character):
{
\tcout << "Hello "
\t << (some + long + expression +
\t to_produce_the_word(world))
\t << endl;
}
In languages like Java, you cannot avoid boilerplate. The best option you have is to check generated code, ensuring that it is the same as what you'd have written by hand. Modify it as necessary. Configure your IDE to generate the exact code that you need, if possible. Eclipse is pretty good at this.
Know what's going on under the hood.
Know that your IDE is actually invoking the compiler. Have some insight into the flags that it passes. Be able to invoke the compiler from the command line.
Know about the runtime system. Be aware of the flags that are used or needed to launch your program. Be able to launch the program from a command line.
I think before anyone uses a RAD tool of any type they should be able to write the application from scratch (scratch being wiring together the framework components) in notepad potentially on a computer that is 10 years older than current technology :P. Not knowing the ins and outs of a paradigm/framework leads to bad code from novice developers who only learn things at a mile high view of the platforms they develop for. Perhaps they should do this in a few technologies -- i.e., GTK programming is completely different to MVC which is then also different to SWING and .NET.
I think the end result should be a developer that thinks of the finer details of a problem before they jump to thinking of how they will write an interface to it in a specific RAD environment.
its an open ended question, but...
We have a Eclipse format file that everyone shares, so that we all format the code in the same manor. (Except the one lone InteliJ guy we have).
Everyone shares a dictionary file. It helps to remove all the red lines from the code. Making it look cleaner and more readable.
I run EMMA over the code to find out who isn't testing their code, and then moan at them.
The main problems we face is that most of the team don't know all the features/power of the IDE (eclipse). The didn't know about CTRL + O (twice), or auto code gen. All I can do as a 'hot key wizard' is keep sharing my knowledge with them to help them become more productive.
I look forward to the day when my problem is that they auto gen as much as possible.
Rather than me finding bugs where the wrong value is returned from a getter method due to a typo.
Attempt development (at least occasionally) using only a text editor and launching the compilation, testing, etc. from the command line.
Typing the commands will get tedious very quickly so create scripts or (even better) learn rake, ant, msbuild.
If the IDE does code generation for you and that code generation is really important (such as generating classes from xsd or proxy classes from wsdl), try to find out how to run the code generation from the command line - then hook the code generation into a build (so you'll never be tempted to edit the generated code).
The idea of autoformatting code is great but it usually just turns your code into a mess. If you have less code, minor formatting inconsistencies are just not a big deal.
Adding code quality tools into your build - style checks, class and method sizes, complexity, code duplication, test coverage, etc (complexian, simian, flog, flay, ndepend, ncover, etc.) will discourage IDE generated code.

When someone writes a new programming language, what do they write it IN?

I am dabbling in PHP and getting my feet wet browsing SO, and feel compelled to ask a question that I've been wondering about for years:
When you write an entirely new programming language, what do you write it in?
It's to me a perplexing chicken & egg thing to me. What do you do? Say to yourself Today I'm going to invent a new language! and then fire up. Notepad? Are all compilers built on previously existing languages, such that were one to bother one could chart all programming languages ever devised onto one monstrous branching tree that eventually grounded out at... I don't know, something old?
It's not a stupid question. It's an excellent question.
As already answered the short answer is, "Another language."
Well that leads to some interesting questions? What if its the very first language written for
your particular piece of hardware? A very real problem for people who work on embedded devices. As already answered "a language on another computer". In fact some embedded devices will never get a compiler, their programs will always be compiled on a different computer.
But you can push it back even further. What about the first programs ever written?
Well the first compilers for "high level languages" would have been written in whats called "assembly language". Assembly language is a language where each instruction in the language corresponds to a single instruction to the CPU. Its very low level language and extremely verbose and very labor intensive to write in.
But even writing assembly language requires a program called an assembler to convert the assembly language into "machine language". We go back further. The very first assemblers were written in "machine code". A program consisting entirely of binary numbers that are a direct one-to-one correspondence with the raw language of the computer itself.
But it still doesn't end. Even a file with just raw numbers in it still needs translation. You still need to get those raw numbers in a file into the computer.
Well believe it or not the early computers had a row of switches on the front of them. You flipped the switches till they represented a binary number, then you flicked another switch and that loaded that single number into the computers memory. Then you kept going flicking switched until you had loaded a minimal computer program that could read programs from disk files or punch cards. You flicked another switch and it started the program running. When I went to university in the 80's I saw computers that had that capacity but never was given the job of loading in a program with the switches.
And even earlier than that computer programs had to be hard wired with plug boards!
The most common answer is C. Most languages are implemented in C or in a hybrid of C with callbacks and a "lexer" like Flex and parser generator like YACC. These are languages which are used for one purpose - to describe syntax of another language. Sometimes, when it comes to compiled languages, they are first implemented in C. Then the first version of the language is used to create a new version, and so on. (Like Haskell.)
A lot of languages are bootstrapped- that is written in themselves. As to why you would want to do this, it is often a good idea to eat your own dogfood.
The wikipedia article I refer to discusses the chicken and egg issue. I think you will find it quite interesting.
Pretty much any language, though using one suited to working with graphs and other complex data structures will make many things easier. Production compilers are often written in C or C++ for performance reasons, but languages such as OCaml, SML, Prolog, and Lisp are arguably better for prototyping the language.
There are also several "little languages" used in language design. Lex and yacc are used for specifying syntax and grammars, for example, and they compile to C. (There are ports for other languages, such as ocamllex / ocamlyacc, and many other similar tools.)
As a special case, new Lisp dialects are often built on existing Lisp implementations, since they can piggyback on most of the same infrastructure. Writing a Scheme interpreter can be done in Scheme in under a page of code, at which point one can easily add new features.
Fundamentally, compilers are just programs that read in something and translate it to something else - converting LaTeX source to DVI, converting C code to assembly and then to machine language, converting a grammar specification to C code for a parser, etc. Its designer specifies the structure of the source format (parsing), what those structures mean, how to simplify the data (optimizing), and the kind of output to generate. Interpreters read the source and execute it directly. (Interpreters are typically simpler to write, but much slower.)
"Writing a new programming language" technically doesn't involve any code. It's just coming up with a specification for what your language looks like and how it works. Once you have an idea of what your language is like, you can write translators and interpreters to actually make your language "work".
A translator inputs a program in one language and outputs an equivalent program in another language. An interpreter inputs a program in some language and runs it.
For example, a C compiler typically translates C source code (the input language) to an assembly language program (the output language). The assembler then takes the assembly language program and produces machine language. Once you have your output, you don't need the translators to run your program. Since you now have a machine language program, the CPU acts as the interpreter.
Many languages are implemented differently. For example, javac is a translator that converts Java source code to JVM bytecode. The JVM is an interpreter [1] that runs Java bytecode. After you run javac and get bytecode, you don't need javac anymore. However, whenever you want to run your program, you'll need the JVM.
The fact that translators don't need to be kept around to run a program is what makes it possible to "bootstrap" your language without having it end up running "on top of" layers and layers of other languages.
[1] Most JVMs do translation behind the scenes, but they're not really translators in that the interface to the JVM is not "input language -> output language".
Actually you can write in almost any language you like to. There's nothing that prevents you from writing a C compiler in Ruby. "All" you have to do is parse the program and emit the corresponding machine code. If you can read/write files, your programming language will probably suffice.
If you're starting from scratch on a new platform, you can do cross-compiling: write a compiler for your new platform, that runs in Java or natively on x86. Develop on your PC and then transfer the program to your new target platform.
The most basic compilers are probably Assembler and C.
Generally you can use just about whatever language you like. PHP was written in C, for example. If you have no access to any compiler whatsoever, you're going to have to resort to writing assembly language and compiling it to machine code by hand.
Many languages were first written in another available language and then reimplemented in itself and bootstrapped that way (or just kept the implementation in the foreign language, like PHP and perl), but some languages, like the first assembler was hand compiled to machine code like the first C-compiler was hand compiled to assembly.
I've been interested in bootstrapping ever since I read about it. To learn more I tried doing it myself by writing my own superset of BF, which i called EBF, in itself. the first version of EBF had 3 extra primitives and I hand compiled the first binary. I found a two step rhythm when doing so. I implemented a feature in the current language in one release and had a sweet release where I rewrote the code to utilize the implemented feature. The language was expressive enough to be used to make a LISP interpreter.
I have the hand compiled version together with the source in the first release tag and the code is quite small. The last version is 12 times bigger in size and the code and allows for more compact code so hand compiling the current version would be hard to get right.
Edmund Grimley Evans did something similar with his HEX language
One of the interesting things about doing this yourself is that you understand why some things are as they are. My code was product if small incremental adjustments an it looks more like it has evolved rather than been designed from scratch. I keep that in mind when reading code today which I think looks a little off.
Usually with a general-purpose programming language suitable for systems development, e.g. C, Haskell, ML, Lisp, etc., but the list of options is long. Also, usually with some domain-specific languages for language implementation, i.e. parser and lexical analyzer generators, intermediate languages like LLVM, etc. And probably some shell scripts, testing frameworks, and a build configuration system, e.g. autoconf.
Most compiler were wriiten C or a c like program if not c then assembly lang is the way to go However when writing a new lang from scratch and you do not have a macro lib or source code from a prototype language you have to define your own functions Now in What Language? You can just write a Form "of source code called psedocode to the machine it looks like a bnf grammar from the object oriented structured lang spec like Fortran basic algo lisp. So image writing a cross code resembling any of these language syntax That's psedo code
What are programming languages in general?
programming languages are a just a way to talk to computers. roughly speaking at first because computers could only understand zeros and ones (due to the fact that computers are made of transistors as switches which could only take two states, we call these two states 0 and 1) and working with 0,1 was hard for us as humans so computer scientists decided to do a one-to-one mapping from every instruction in binary(0,1) to a more human readable form which they called it assembly language.
for example if we had an instruction like:
11001101
in assembly it would be called:
LOAD_A 15
which means that load the content of register a into memory location 15. as i said it was just a convention like choosing 0 and 1 for two states of the transistors or anything else in the computer.in this way having a program with 50 instructions , remembering the assembly language would be easier . so the user would write the assembly code and some program (assembler in this case) would translate the codes to binary instructions or machine language as they call it.
but then with the computers getting improved every day there was room for more complicated programs with more instructions, say 10000.
in this case a one-to-one mapping like assembly wouldn't work, so other high level programming languages were created. they said for example if for a relation with I/O devices for printing something on the screen created by the user takes about 80 instructions , let us do something in here and we could package all this code into one library and call it for example printf and also create another program which could translate this printf in here to the related assembly code and from there the assembly would do the rest. so they call it compiler.
so now every user who wants to just print something on the screen he wouldn't have to write all the instructions in binary or assembly he just types printf("something") and all the programs like the compiler and assembler would do the rest. now later other longer codes would be packaged in the same way to just facilitate the work of other people as you see that you could just simplify a thousands line of code into one code in python and pack it for the use of other people.
so let's say that you have packed a lot of different codes in python and created a module(libray, package or anything that you want to call it) and you call that module mgh(just my name). now let's say we have created this mgh somehow that any one who says:
import mgh
mgh.connect(ip,port.data)...
could easily connect to a remote server with the ip and port number specified and send the data afterwards(or something like that). now people could do all of it using one single line, but what that happens is that a lot of codes are getting executed which have been retrieved from the mgh file. and packaging it has not been for speeding up the process of execution but rather facilitating other programmers works. so in here if someone wants to use your code first he should import the file and then the python interpreter would recognize all the code in it and so it could interpret the code.
now if you want to create a programming language and you want to execute it , first it needs a translation, for example let's say that you create a program which could understand the syntax and convert it to c , in this case after it has been translated to c , the rest would be taken care of , by the c compiler , then assembler , linker, ... .
even though you would have to pay the price of being slower since it has to be converted to c first.
now one other thing that you could do is to create a program which could translate all the code to the equivalent assembly language just like what happens with c but in this case the program could do it directly and from there the rest would be done by the linker. we know that this program is called compiler.
so what i am talking about is that, the only code that the system understands is 0,1 , so somehow you should convert you syntax to that, now in our operating systems a lot of different programs like assembler, linker and ... have been created to tell you that if you could convert your code to assembly they could take care of the rest or as i said you could even use other programming languages compilers by converting your code to that language.
Even further binary ,or assembly operations must be translated into functions, thats the assemblers/compilers job, then into object,from data and functions, if you don't have a source file to see" how these objects functionality should be represented in your language implementation ,Then you have to recognize "see" implement, or define your own functions ,procedures, and data structures, Which requires a lot of knowledge, you need to ask yourself what is a function.Your mind then becomes the language simulation.This Separate a Master programmer from the rest.
I too had this question few months back. And I read few articles and watched some videos which helped me to start writing my own language called soft. Its not complete yet but I learned a lot of stuff from this journey.
Basic things you should know is how compiler works when it has to execute a code snippet. Compiler has a lot of phases like lexical analysis, semantic analyzer, AST(Abstract Syntax Tree) etc.
What I did in my new language can be found here - http://www.singhajit.com/writing-a-new-programming-language/
If you are writing a language for first time then all the best and you have a long way to go.

How would one go about testing an interpreter or a compiler?

I've been experimenting with creating an interpreter for Brainfuck, and while quite simple to make and get up and running, part of me wants to be able to run tests against it. I can't seem to fathom how many tests one might have to write to test all the possible instruction combinations to ensure that the implementation is proper.
Obviously, with Brainfuck, the instruction set is small, but I can't help but think that as more instructions are added, your test code would grow exponentially. More so than your typical tests at any rate.
Now, I'm about as newbie as you can get in terms of writing compilers and interpreters, so my assumptions could very well be way off base.
Basically, where do you even begin with testing on something like this?
Testing a compiler is a little different from testing some other kinds of apps, because it's OK for the compiler to produce different assembly-code versions of a program as long as they all do the right thing. However, if you're just testing an interpreter, it's pretty much the same as any other text-based application. Here is a Unix-centric view:
You will want to build up a regression test suite. Each test should have
Source code you will interpret, say test001.bf
Standard input to the program you will interpret, say test001.0
What you expect the interpreter to produce on standard output, say test001.1
What you expect the interpreter to produce on standard error, say test001.2 (you care about standard error because you want to test your interpreter's error messages)
You will need a "run test" script that does something like the following
function fail {
echo "Unexpected differences on $1:"
diff $2 $3
exit 1
}
for testname
do
tmp1=$(tempfile)
tmp2=$(tempfile)
brainfuck $testname.bf < $testname.0 > $tmp1 2> $tmp2
[ cmp -s $testname.1 $tmp1 ] || fail "stdout" $testname.1 $tmp1
[ cmp -s $testname.2 $tmp2 ] || fail "stderr" $testname.2 $tmp2
done
You will find it helpful to have a "create test" script that does something like
brainfuck $testname.bf < $testname.0 > $testname.1 2> $testname.2
You run this only when you're totally confident that the interpreter works for that case.
You keep your test suite under source control.
It's convenient to embellish your test script so you can leave out files that are expected to be empty.
Any time anything changes, you re-run all the tests. You probably also re-run them all nightly via a cron job.
Finally, you want to add enough tests to get good test coverage of your compiler's source code. The quality of coverage tools varies widely, but GNU Gcov is an adequate coverage tool.
Good luck with your interpreter! If you want to see a lovingly crafted but not very well documented testing infrastructure, go look at the test2 directory for the Quick C-- compiler.
I don't think there's anything 'special' about testing a compiler; in a sense it's almost easier than testing some programs, since a compiler has such a basic high-level summary - you hand in source, it gives you back (possibly) compiled code and (possibly) a set of diagnostic messages.
Like any complex software entity, there will be many code paths, but since it's all very data-oriented (text in, text and bytes out) it's straightforward to author tests.
I’ve written an article on compiler testing, the original conclusion of which (slightly toned down for publication) was: It’s morally wrong to reinvent the wheel. Unless you already know all about the preexisting solutions and have a very good reason for ignoring them, you should start by looking at the tools that already exist. The easiest place to start is Gnu C Torture, but bear in mind that it’s based on Deja Gnu, which has, shall we say, issues. (It took me six attempts even to get the maintainer to allow a critical bug report about the Hello World example onto the mailing list.)
I’ll immodestly suggest that you look at the following as a starting place for tools to investigate:
Software: Practice and Experience April 2007. (Payware, not available to the general public---free preprint at http://pobox.com/~flash/Practical_Testing_of_C99.pdf.
http://en.wikipedia.org/wiki/Compiler_correctness#Testing (Largely written by me.)
Compiler testing bibliography (Please let me know of any updates I’ve missed.)
In the case of brainfuck, I think testing it should be done with brainfuck scripts. I would test the following, though:
1: Are all the cells initialized to 0
2: What happens when you decrement the data pointer when it's currently pointing to the first cell? Does it wrap? Does it point to invalid memory?
3: What happens when you increment the data pointer when it's pointing at the last cell? Does it wrap? Does it point to invalid memory
4: Does output function correctly
5: Does input function correctly
6: Does the [ ] stuff work correctly
7: What happens when you increment a byte more than 255 times, does it wrap to 0 properly, or is it incorrectly treated as an integer or other value.
More tests are possible too, but this is probably where i'd start. I wrote a BF compiler a few years ago, and that had a few extra tests. Particularly I tested the [ ] stuff heavily, by having a lot of code inside the block, since an early version of my code generator had issues there (on x86 using a jxx I had issues when the block produced more than 128 bytes or so of code, resulting in invalid x86 asm).
You can test with some already written apps.
The secret is to:
Separate the concerns
Observe the law of Demeter
Inject your dependencies
Well, software that is hard to test is a sign that the developer wrote it like it's 1985. Sorry to say that, but utilizing the three principles I presented here, even line numbered BASIC would be unit testable (it IS possible to inject dependencies into BASIC, because you can do "goto variable".