ANTLR: loop did not match anything at input - eclipse

sorry for my english! I have problem, faced here with such a problem, give the decision:
line 1:0 required (...)+ loop did not match anything at input < E O F
>
This my file, calc.g
grammar calc;
options {
language = Java;
}
rule: statement+;
statement
: expr NEWLINE
| ID '=' expr NEWLINE
| NEWLINE
;
NEWLINE : '\r'? '\n'
;
expr
: multExpression ('+' multExpression |'-' multExpression)*
;
multExpression
: a1=atom ('*' a2=atom | '/' a2=atom)*
;
atom
: ID
| INT
| '(' expr ')'
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : ('1'..'9') ('0'..'9')*
;
this is my main:
ANTLRReaderStream input = new ANTLRReaderStream();
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();

It looks like your input is empty: the parser immediately encounters the EOF (end-of-file) where it expects at least one statement.
Try something like this:
ANTLRStringStream input = new ANTLRStringStream("2*42\n");
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();
As 280Z28 mentioned in the comment beneath my answer, you should probably force the parser to consume the entire input by adding EOF at the end of your parser's entry point:
rule: statement+ EOF;
and if you want to allow an empty string to be valid input too, change the + to a *;
rule: statement* EOF;

I didn't test it but think you have to add the default EOF token to your grammar:
rule: statement+ EOF!;
Your parser seems to recognize the whole input but at the end there is an EOF but you did not add the corresponding rule to your grammar.

Related

Ghostscript ps2pdf not Working Correctly from MATLAB

I have a .tex file I am attempting to write from a MATLAB environment (2017b) using first latex, then dvips, and finally ps2pdf to create the PDF file. The PDF file is properly created when I run it through TeXWorks, but sends an error from ps2pdf when I try to run it through. I'm not entirely sure what's wrong with the way I send it to the command line. Here is the script I am attempting to run.
set(groot, 'defaultAxesTickLabelInterpreter','latex');
set(groot, 'defaultLegendInterpreter','latex');
set(0,'defaultTextInterpreter','latex');
addpath('C:\Program Files (x86)\MiKTeX\miktex\bin\x64')
exampledir='\\our\server\';
examplefilename='test';
texdoc=fullfile(exampledir,strcat(examplefilename,'.tex'));
auxdoc=fullfile(exampledir,strcat(examplefilename,'.aux'));
logdoc=fullfile(exampledir,strcat(examplefilename,'.log'));
dvidoc=fullfile(exampledir,strcat(examplefilename,'.dvi'));
psdoc=fullfile(exampledir,strcat(examplefilename,'.ps'));
pdfdoc=fullfile(exampledir,strcat(examplefilename,'.pdf'));
fileID = fopen(texdoc,'w');
textext=['\documentclass[twoside]{article} %Two-sided document. Required for fancyhf left and right page numbering scheme current.' newline ...
'\usepackage{graphicx}' newline ...
newline ...
'\usepackage{fancyhdr} %Use the package fancy header/footer' newline ...
newline ...
'\usepackage[letterpaper,margin=0.5in,bottom=0.75in,top=0.7in]{geometry} %Ensure the paper is letterpaper.' newline ...
'\usepackage{grffile}' newline ...
'\usepackage{caption}' newline ...
'\usepackage{float} %Float used to position graphics.' newline ...
'\usepackage{lastpage209} %For last page' newline ...
newline ...
'\DeclareGraphicsExtensions{.PDF,.jpg} %Notify LaTeX what type of graphics extensions to expect.' newline ...
newline ...
'\renewcommand{\headrulewidth}{0pt} % remove the header rule' newline ...
newline ...
'\fancyhf{} % clear all header and footers' newline ...
newline ...
'\pagestyle{fancy} %Use the fancy pagestyle, which will include the fancy header and footer options we defined above.' newline ...
newline ...
'\setlength\headheight{38pt} ' newline ...
newline ...
'\fancyhead[L]{{Page \thepage} of \pageref{LastPage}} %Left side on even pages; right side on odd pages.' newline ...
'\fancyhead[R]{\includegraphics[trim={0.3in 0.26in 0.05in 0.26in},clip,width=0.4in]{{\\our\server\mypicture}}}' newline ...
newline ...
'\begin{document} %This will be the actual document and what goes into it.' newline ...
newline ...
'\begin{figure}[h] %Make a figure...' newline ...
newline ...
' \includegraphics[trim={0.25in 0 0 0},clip,width=7.5in]{{\\our\server\mypicture}}' newline ...
newline ...
' \captionsetup{labelformat=empty}' newline ...
newline ...
'\end{figure}' newline ...
newline ...
'\end{document}'];
fprintf(fileID,'%s',textext);
fclose(fileID);
% latex dvips ps2pdf
% text.tex -------> text.dvi -------> text.ps --------> text.pdf
[~,cmdoutlatex] = system(['latex.exe -interaction=nonstopmode -output-directory ' exampledir '\ ' texdoc]);
if contains(cmdoutlatex,'Sorry, but latex.exe did not succeed.')
%Do some kind of check and fix things.
end
[~,cmdoutdvips] = system(['dvips.exe -q* -o ' psdoc ' ' dvidoc]);
if contains(cmdoutdvips,'!')
%Do some kind of check and fix things.
error(['Error: ' cmdoutdvips])
end
[~,cmdoutps2pdf] = system(['ps2pdf ' psdoc ' ' pdfdoc ' -sDEVICE=pdfwrite']);
if contains(cmdoutps2pdf,'Error','IgnoreCase',true)
%Do some kind of check and fix things.
error(cmdoutps2pdf)
end
Per #Cris Luengo's suggestion of moving to pdflatex rather than using latex/dvips/ps2pdf commands, this worked. Here is the sample code of what worked for a system command.
[~,pdflatexout] = system(['pdflatex.exe -output-directory ' strrep(exampledir,'\','/') ' ' texdoc]);
%Check for errors.
if contains(pdflatexout,'Sorry, but pdflatex.exe did not succeed.') || ...
contains(pdflatexout,'error','IgnoreCase',true)
%Deliver the error code.
error(pdflatexout)
end
I placed this after fclose(fileID) in the original code and deleted all that had originally come after that line.

ultisnips: How to "freeze" vim.current.window.cursor value for snippet

I had a snippet that used to work well (neovim 0.2.0)
snippet #= "comment ===" b
# `!p snip.rv = '=' * (78 - vim.current.window.cursor[1])`
# ${1:comments}
# `!p snip.rv = '=' * (78 - vim.current.window.cursor[1])`
endsnippet
This snippet is basically writing python comments block when triggered,
where the length of "=" depends on the position of the cursor.
For a few days now (I don't know which update makes it failing), the length of "=" is decreasing as long as I type my comment.
It looks like vim.current.window.cursor[1] is constantly re-evaluated.
Any idea how to "freeze" the value?
I finally found:
snippet #= "comment ===" b
`!p
if not snip.c:
width = int(vim.eval("78 - virtcol('.')"))
snip.rv = '# ' + '=' * width`
# ${1:comments}
`!p snip.rv = '# ' + '=' * width`
endsnippet

Xtext 2.8+ formatter, formatting HiddenRegion with comment

I am using Xtext 2.9 formatter and I am trying to format hiddenRegion which contains comment. Here is part of my document region i am trying to format:
Columns: 1:offset 2:length 3:kind 4: text 5:grammarElement
Kind: H=IHiddenRegion S=ISemanticRegion B/E=IEObjectRegion
35 0 H
35 15 S ""xxx::a::b"" Refblock:namespace=Namespace
50 0 H
50 1 S "}" Refblock:RCBRACKET
E Refblock PackageHead:Block=Refblock path:PackageHead/Block=Package'xxx_constants'/head=Model/packages[0]
51 0 H
51 1 S ":" PackageHead:COLON
E PackageHead Package:head=PackageHead path:Package'xxx_constants'/head=Model/packages[0]
52 >>>H "\n " Whitespace:TerminalRule'WS'
"# asd" Comment:TerminalRule'SL_COMMENT'
15 "\n " Whitespace:TerminalRule'WS'<<<
B Error'ASSD' Package:expressions+=Expression path:Package'xxx_constants'/expressions[0]=Model/packages[0]
67 5 S "error" Error:'error'
72 1 H " " Whitespace:TerminalRule'WS'
and corresponding part of the grammar
Model:
{Model}
(packages+=Package)*;
Expression:
Error | Warning | Enum | Text;
Package:
{Package}
'package' name=Name head=PackageHead
(BEGIN
(imports+=Import)*
(expressions+=Expression)*
END)?;
Error:
{Error}
('error') name=ENAME parameter=Parameter COLON
(BEGIN
(expressions+=Estatement)+
END)?;
PackageHead:
Block=Refblock COLON;
Problem is that when i try prepend some characters before error keyword
for example
error.regionFor.keyword('error').prepend[setSpace("\n ")]
This indentation is prepended before the comment and not behind it. This results into improper formatting in case of single line comment before the 'error' keyword.
To provide more clarity, here is example code from my grammar and description of desired behavior:
package xxx_constants {namespace="xxx::a::b"}:
# asd
error ASSD {0}:
Hello {0,world}
This is expected result: (one space to the left)
package xxx_constants {namespace="xxx::a::b"}:
# asd
error ASSD {0}:
Hello {0,world}
and this is the actual result with prepend method
package xxx_constants {namespace="xxx::a::b"}:
# asd
error ASSD {0}:
Hello {0,world}
As the document structure says, the HiddenRegion is in this case is the statement:
# asd
error
How can i prepend my characters directly before the keyword 'error' and not before the comment? Thanks.
I assume you're creating an indentation-sensitive language, because you're explicitly calling BEGIN and END.
For indentation-sensitive language my answer is: You'll want to overwrite
org.eclipse.xtext.formatting2.internal.HiddenRegionReplacer.applyHiddenRegionFormatting(List<ITextReplacer>)
The methods append[] and prepend[] you're using are agnostic to comments and at a later time applyHiddenRegionFormatting() is called to decide how that formatting is weaved between comments.
To make Xtext use your own subclass of HiddenRegionReplacer, overwrite
org.eclipse.xtext.formatting2.AbstractFormatter2.createHiddenRegionReplacer(IHiddenRegion, IHiddenRegionFormatting)
For languages that do not do whitespace-sensitive lexing/parsing (that's the default) the answer is to not call setSpace() to create indentation or line-wraps.
Instead, do
pkg.interior[indent]
pkg.regionFor.keyword(":").append[newLine]
pkg.append[newLine]

What does the line ## -9,9 +9,10 ## mean in a diff file?

Can someone please explain the third line in the sample diff output below (i.e., the one that starts with ##)? I understand the changes represented by the remaining lines but am having trouble making sense of that third line...
--- a/code/c-skeleton/Makefile
+++ b/code/c-skeleton/Makefile
## -9,9 +9,10 ##
TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))
## -9,9 +9,10 ##
...specifies where in the source and destination files changes take place, by line number and size of the chunk being edited, both before and after the changes.
Specifically:
## -9,9 +9,10 ##
^ ^^ ^ ^^ ^
| || | || \----- The "10" is the number of lines in the hunk after being
| || | || modified; this patch, then, must add a line, since the
| || | || new count (of 10) is longer than the old count (of 9).
| || | |\------- This "9" is the line number in the new file where the
| || | | modified hunk is placed.
| || | \-------- This "+" is a hint that the following numbers refer to
| || | the new file, after modification.
| || \---------- This "9" is the number of lines in the hunk before being
| || modified.
| |\------------ This "9" is the line number in the original file.
| \------------- This "-" is a hint that the following numbers refer to the
| original file.
\---------------- This "##" is a marker indicating that this is the start of a
new hunk.
That is to say: in the original file, the hunk being modified consists of 9 lines starting at line 9; in the destination file, it's 10 lines starting at line 9.
See the detailed description of unified diff format in the GNU diffutils documentation.

Advanced Command-Line Replace Command In VBScript

I'm writing a compiler for my won computer language. Now before the language can be compiled i actually need to replace all apostrophes (') with percents (%) via a command-line vbs program. But the apostrophes only need to be replaced if there is NOT a circumflex accent (^) in front of it. So for example, in this code:
color 0a
input twelve = 0a "hi! that^'s great! "
execute :testfornum 'twelve'
exit
:testfornum
if numeric('1) (
return
) ELSE (
print 0a "oops 'twelve' should be numeric"
)
return
the apostrophe at line 2 should not be replaced, but the ones at line 3, 6 and 9 should be.
can anyone help me?
this is what i have so far:
'syntax: (cscript) replace.vbs [filename] "StringToFind" "stringToReplace"
Option Explicit
Dim FileScriptingObject, file, strReplace, strReplacement, fileD, lastContainment, newContainment
file=Wscript.arguments(0)
strReplace=WScript.arguments(1)
strReplacement=WScript.arguments(2)
Set FileScriptingObject=CreateObject("Scripting.FileSystemObject")
if FileScriptingObject.FileExists(file) = false then
wscript.echo "File not found!"
wscript.Quit
end if
set fileD=fileScriptingobject.OpenTextFile(file,1)
lastContainment=fileD.ReadAll
newContainment=replace(lastContainment,strReplace,strReplacement,1,-1,0)
set fileD=fileScriptingobject.OpenTextFile(file,2)
fileD.Write newContainment
fileD.Close
As #Ansgar's solution fails for the special case of a leading ' (no non-^ before that), here is an approach that uses a replace function in a test script that makes further experiments easy:
Option Explicit
Function fpR(m, g1, g2, p, s)
If "" = g1 Then
fpR = "%"
Else
fpR = m
End If
End Function
Function qq(s)
qq = """" & s & """"
End Function
Dim rE : Set rE = New RegExp
rE.Global = True
rE.Pattern = "(\^)?(')"
Dim rA : Set rA = New RegExp
rA.Global = True
rA.Pattern = "([^^])'"
'rA.Pattern = "([^^])?'"
Dim s
For Each s In Split(" 'a^'b' a'b'^'c nix a^''b")
WScript.Echo qq(s), "==>", qq(rE.Replace(s, GetRef("fpR"))), "==>", qq(rA.Replace(s, "$1%"))
Next
output:
cscript 25221565.vbs
"" ==> "" ==> ""
"'a^'b'" ==> "%a^'b%" ==> "'a^'b%" <=== oops
"a'b'^'c" ==> "a%b%^'c" ==> "a%b%^'c"
"nix" ==> "nix" ==> "nix"
"a^''b" ==> "a^'%b" ==> "a^'%b"
You can't do this with a normal string replacement. A regular expression would work, though:
...
Set re = New RegExp
re.Pattern = "(^|[^^])'"
re.Global = True
newContainment = re.Replace(lastContainment, "$1%")
...