unexpected T_OBJECT_OPERATOR but no TypeChecker errors (Hacklang) - hacklang

<?hh //strict
foreach ($list as $id) {
$items = new DestinationsByCountry($id);
$remapped = $items->byKey('destination_id')->map($stringed ==> (int) $stringed);
$this->ids->addAll($remapped);
}
foreach ($list as $id) {
$this->ids->addAll(
// ******* error line below *******
new DestinationsByCountry($id)
->byKey('destination_id')
->map($stringed ==> (int) $stringed)
);
}
Both is OK for the typecheker, but the second cause fatal error
Fatal error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ')'

As pointed out in the comments above, you need parenthesis around (new DestinationsByCountry($id)), in both PHP and in Hack syntax.
The reason the typechecker doesn't complain is because it doesn't typecheck code at toplevel. If this had been inside a function or method, I expect the typechecker would have found the error. If this code was in fact inside a function or method, please do file an issue on GitHub.

Related

Puppet stdlib keys() function syntax error

I'm sure I'm doing something silly, but I can't work out the correct syntax for the stdlib keys() function and can't find any examples on the internet.
Here is what I've tried:
file { ["/tmp/file1", "/tmp/file2"]: # <-- this works as expected
ensure => present,
}
$hash = {"/tmp/file1" => 1, "/tmp/file2" => 2}
file { keys($hash): # <-- syntax error occurs here
ensure => present,
}
It results in this error:
Error: Could not retrieve catalog from remote server: Error 400 on
SERVER: Syntax error at ':'; expected '}' at
/etc/puppet/modules/slony/manifests/master.pp:113 on node slonymaster
What am I missing? I'm using Puppet 3.6.2 with stdlib 4.3.2.
You are just overtaxing your expressions. The idea is sound, but you will have to take an intermediate step.
$filenames = keys($hash)
file { $filenames: ensure => present }
Puppet will only accept literal array values or variables as resource titles.

Get rid of token recognition error

How can I get rid of the default ANTLR recognition error?
I want to write another message using my own error class instead of ANTLR's error.
I mean is there any possibility that some ANTLR error classes can be extended in order to display my own message?
More clearly, I do not want to see the following error message in my console :
token recognition error at:
If you simply want to suppress the messages, you can call lexer.removeErrorListeners(). However, a better approach is writing your lexer rules such that all possible input is tokenized, with the following rule at the end of the lexer. This will cause all error reporting to go through the parser instead of both the parser and lexer.
// handle characters which failed to match any other token
ErrorCharacter : . ;
In order to create a custom error handler you can extend the BaseErrorListener class and override the syntaxError method, e.g.:
public class MyErrorListener extends BaseErrorListener {
#Override
public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e ) {
// method arguments should be used for more detailed report
throw new RuntimeException("syntax error occurred");
}
}
Now when you create a lexer and a parser you should remove the default error listeners and attach your custom one:
MyErrorListener errorListener = new MyErrorListener();
Lexer lexer = new MyLexer( ... );
lexer.removeErrorListeners();
lexer.addErrorListener( errorListener );
CommonTokenStream tokens = new CommonTokenStream( lexer );
Parser parser = new MyParser( tokens );
parser.removeErrorListeners();
parser.addErrorListener( errorListener );
The default message "line x:x token recognition error at: 'xxx'" comes from the default ConsoleErrorListener class. If you don't remove it using lexer/parser.removeErrorListeners() and only add your custom one it will still be triggered.
The error handling strategies are thoroughly described in a dedicated chapter of The Definitive ANTLR4 Reference book (mentioned on the ANTLR4 Documentation page). I currently have no access to the book itself, so would be grateful if someone edits this answer with a concrete page number of the book. Also, I couldn't find a related guide on the ANTLR4 doc page, so if it exists - a link would be helpful, too.

Twig and error messages - is this normal?

I've been testing Twig on localhost... the code here is the same as in this question but the query is different:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, modelinfo FROM automobiles WHERE id = '4' ";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
I have 3 records; I decided to query a non-existent record to see what Twig's error handling was like, as I was comparing Twig vs Smarty - out of interest, and for a project.
This error message comes up:
Notice: Undefined variable: data in /Applications/MAMP/htdocs/mysite/twigtesting.php on line 42
Surely a notice saying 'Data not found' should happen or am I wrong here?
Undefined variable data refers to:
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
Why is this happening? I'm new to Twig, and using the latest build from their site, f that's relevant.
You don't get a Twig error, because the error does not exists in the templates, but in the code that is generating these templates.
PHP is having issues to put the value of $data inside an array, because that variable does not exists.
If you want to see how twig handles errors, you need to access a non existing variable inside a template. For instance, putting {{ notExisting }} in your current template.
I can already say that Twig is handling errors by throwing parsing exceptions in PHP. All exceptions thrown by Twig are extending Twig_Error. To catch these, use a try { ... } catch (\Twig_Error $e) { ... } block.
Furthermore, Twig can throw 3 different types of Exceptions:
Twig_Error_Syntax is thrown when an error occurs when parsing a template (e.g. using malformed tags).
Twig_Error_Loader is thrown when Twig can't load a file. This can happen when using a render() method, or when you use some file features in Twig (e.g. {% extends ... %}).
Twig_Error_RunTime is thrown when an error occurs in runtime (e.g. an error inside extensions).

WinRT Asynchronous File operations in C++

I'm currently working on a metro app that requires a few textual resources. Part of the build process is copying all of these resources to a folder inside of the app's installation directory. What I'd like to do is gather a list of these resource files, and process each one accordingly. Unfortunately, my attempts to do so have been less than successful.
Since I'm building for WinRT, I can't use the very useful "FindFirstFile" and "FindNextFile" functions. I've been trying to get the job done using the WinRT Asynchronous file IO operations.
auto getResourceFolder = installedLocation->GetFolderFromPathAsync( folderPath );
getResourceFolder->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler< Windows::Storage::StorageFolder^ >(
[this]( Windows::Foundation::IAsyncOperation< Windows::Storage::StorageFolder^ >^ operation ) {
if( operation->Status == Windows::Foundation::AsyncStatus::Completed ) {
auto resourceFolder = operation->GetResults();
auto getResourceFiles = resourceFolder->GetFilesAsync();
getResourceFiles->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler< IVectorView< Windows::Storage::IStorageFile^ >^ >(
[this]( Windows::Foundation::IAsyncOperation< IVectorView< Windows::Storage::IStorageFile^ >^ >^ operation ) {
if( operation->Status == Windows::Foundation::AsyncStatus::Completed ) {
auto resourceFiles = operation->GetResults();
for( unsigned int i = 0; i < resourceFiles->Size; ++i ) {
// Process File
}
}
});
}
});
Which fails to compile:
error C2664: 'Windows::Foundation::IAsyncOperation<TResult>::Completed::set' : cannot convert parameter 1 from 'Windows::Foundation::AsyncOperationCompletedHandler<TResult> ^' to 'Windows::Foundation::AsyncOperationCompletedHandler<TResult> ^'
The error isn't making any sense to me. I've tried rewriting the above code so that the lambda handler functions are not inline, but it hasn't made a difference. I'm not sure what's wrong.
Any ideas? Thanks in advance.
[Note: I have omitted most namespace qualification from the code and error messages for brevity.]
The Visual Studio Error List pane only shows the first line of each error (this is a very useful feature, especially when programming in C++, because some error messages from the compiler are exceedingly long. You need to look at the Output window to see the rest of the error message:
error C2664: 'IAsyncOperation<TResult>::Completed::set' :
cannot convert parameter 1
from 'AsyncOperationCompletedHandler<TResult> ^'
to 'AsyncOperationCompletedHandler<TResult> ^'
with
[
TResult=IVectorView<StorageFile ^> ^
]
and
[
TResult=IVectorView<IStorageFile ^> ^
]
and
[
TResult=IVectorView<StorageFile ^> ^
]
No user-defined-conversion operator available, or
Types pointed to are unrelated;
conversion requires reinterpret_cast, C-style cast or function-style cast
This is still a bit confusing because all three templates use a parameter named TResult. To decipher the error, note that the order of the templates in the first line matches the order of the template argument lists in the rest of the line.
The issue here is that you are mixing usage of StorageFile and IStorageFile. On both of these lines, you need to use StorageFile (see carrots under lines for where IStorageFile is used):
getResourceFiles->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler< IVectorView< Windows::Storage::IStorageFile^ >^ >(
^
[this]( Windows::Foundation::IAsyncOperation< IVectorView< Windows::Storage::IStorageFile^ >^ >^ operation ) {
^
Note that once you fix this issue, you'll get another pair of errors because your lambdas need to have two parameters; the second is an AsyncStatus. In the end, they should both be declared as:
// Namespaces omitted for brevity
[this](IAsyncOperation<StorageFolder^>^ operation, AsyncStatus status) { }
Since I'm building for WinRT, I can't use the very useful FindFirstFile and FindNextFile functions.
Note that you can, in fact, use both FindFirstFileEx and FindNextFile in a Metro style app. (The non-Ex FindFirstFile is not usable).
You should use the asynchronous WinRT functions wherever you can and wherever it is practical, but that doesn't mean there isn't still a use for these other functions.
A far simpler solution is to use PPL for your async operations. Instead of manually rolling the async operation, try:
create_task(installedLocation->GetFolderFromPathAsync(folderPath)
.then([this](Windows::Storage::StorageFolder^ folder) {
return folder->GetFilesAsync();
})
.then([this](IVectorView<Windows::Storage::StorageFile^ >^ files) {
for( unsigned int i = 0; i < files->Size; ++i ) {
// Process File
}
});
I'm not 100% on the syntax, this was written in the SO code editor, but it shows how PPL dramatically reduces the complexity of this kind of code - basically you use create_task to create a task, then use the .then method on the task to specify a lambda which is used for async completion.
EDIT: Updated to remove the nested lambda.

is a 'variable' but is used like a 'method'

I attempted to search for a solution on google and on SO but was not able to resolve my issue.
My code is:
try
{
objEmployerAuditReportData empAuditData = new objEmployerAuditReportData();
IList<EmployerAuditReport> listAuditBatchList = empAuditData.GetAuditBatchList();
foreach (var batchList in listAuditBatchList)
{
IList<EmployerAuditReport> listAuditBatchDetails = empAuditData.GetAuditBatchDetails(listAuditBatchList("form_request_id"));
}
string PDFexportFileName="";
string PDFexportFilePath = System.Configuration.ConfigurationManager.AppSettings["PDFReportPath"];
}
catch (Exception ex)
{
throw ex;
}
error message:
'listAuditBatchList' is a 'variable' but is used like a 'method'
I know this seems very simple, but I can't figure it out. Your assistance is greatly appreciated.
UPDATE:
This turned out to be an application architecture related issue. The correct solution was:
empAuditData.GetAuditBatchDetails(batchList.<propertyname>)
and form_request_id had to be set as a property "set" and "get"
It is where you "call" listAuditBatchList with parentheses and a string argument, "form_request_id".
listAuditBatchList is a list of EmployerAuditReport, so there is no way to call it as a method, and no string keys if you meant listAuditBatchList["form_request_id"].
You have to use squre brackets([form_request_id]) instead listAuditBatchList("form_request_id").Other wise it will method.

Resources