Selective compilation - programming-languages

I'm wondering is there a capability, in any programming language, that I can choose to compile only a certain part of code. See example below.
This is a block of pseudocode:
function foo() {
if (isDebug) {
checkSomethingForDebugging();
print(some debug info);
}
toSomeFooThings();
}
This block is for debugging purpose, I want to ignore them (even the if statement) in production.
if (isDebug) {
checkSomethingForDebugging();
print(some debug info);
}
One thing I can do is to comment out these lines,
function foo() {
//if (isDebug) {
// checkSomethingForDebugging();
// print(some debug info);
//}
toSomeFooThings();
}
But what if I have thousands of places like this? It will be good if there is a way (a flag) that I can choose to compile a certain part of the code or not. It's like a debugging build. Is there anything for this in any programming language? I did search online but was no luck.

Most languages don't have this, but you could certainly write a script which processed the source code somewhere in your build/deploy pipeline and deleted the debug only parts. An advanced way would be to properly parse the source code and delete the appropriate if blocks. For Python this would be quite easy using either the ast module or just looking for lines saying if is_debug: and then watching the indentation level. For other languages it might be harder. A simpler way in terms of the preprocessing script would be to use delimiting comments:
// DEBUGONLY
checkSomethingForDebugging();
print(some debug info);
// ENDDEBUGONLY
In this case the if statement is optional depending on how exactly you want to do things.

Well, that depends on the compiler you are using. For example, in GCC for the C programming language, you have a whole set of preprocessor instructions that could be used for that.
For example:
#ifdef DEBUG
// Your code here...
#endif /* DEBUG */
And, when you are compiling the debug version, you just have to include an extra header that defines the DEBUG macro. There's no need of setting any value, just define it.
#define DEBUG
And that's it.

There are languages (including C, C++ and C#) that can do this using preprocessor directives like #if or #ifdef:
#if DEBUG
checkSomethingForDebugging();
print(some debug info);
#endif
When the code is compiled, if the DEBUG symbol is not set, the code between the two directives is not compiled at all (and doesn't even have to be valid code).
But more importantly, why are you asking? If you're worried about performance, then such checks are very cheap (since they are easily predicted). And if the checks are written right (e.g. if isDebug is a global constant) and compiled using a good compiler, they can even be eliminated as dead code, which makes them completely free.

Related

node.js most performant way to skip a part of code

In compiling languages like C we have a preprocessor that can be used to skip parts of program without compiling them, effectively just excluding them from the source code:
#ifdef SHOULD_RUN_THIS
/* this code not always runs */
#endif
So that if SHOULD_RUN_THIS is not defined, then the code will never be run.
In node.js we don't have a direct equivalent of this, so the first thing I can imagine is
if (config.SHOULD_RUN_THIS) {
/* this code not always runs */
}
However in node there is no way to guarantee that config.SHOULD_RUN_THIS will never change, so if (...) check will be performed each time in vain.
What would be the most performant way to rewrite it? I can think of
a) create a separate function to allow v8-optimizations:
function f(args) {
if (config.SHOULD_RUN_THIS) {
/* this code not always runs */
}
}
// ...
f(args);
b) create a variable to store the function and set it to an empty function when not needed:
var f;
if (config.SHOULD_RUN_THIS) {
f = (args) => {
/* this code not always runs */
}
}
else {
f = function () {} // does nothing
}
// ...
f(args);
c) do not create a separate function, just leave it in place:
if (config.SHOULD_RUN_THIS) {
/* this code not always runs */
}
What is the most performant way? Maybe some other way...
i personally would adopt ...
if (config.SHOULD_RUN_THIS) {
require('/path/for/conditional/module');
}
the module code is only required where needed, otherwise it is not even loaded in memory let alone executed.
the only downside is that it is not readily clear which modules are being required since your require statements are not all positioned at the top of the file.
es6 modularity adopts this dynamic module request approach.
PS use of config like this is great since, you can for example, use an environment variable to determine your code path. Great when spinning up, for example, a bunch of docker containers that you want to behave differently depending on the env vars passed to the docker run statements.
apologies for this insight if you are not a docker fan :) apologies i am waffling now!
if you're looking for a preprocessor for your Javascript, why not use a preprocessor for your Javascript? It's node-compatible and appears to do what you need. You could also look into writing a plugin for Babel or some other JS mangling tool (or v8 itself!)
If you're looking for a way to do this inside the language itself, I'd avoid any optimizations which target a single engine like v8 unless you're sure that's the only place your code will ever run. Otherwise, as has been mentioned, try breaking out conditional code into a separate module so it's only loaded if necessary for it to run.

how to switch off nodejs utilities debug

after some time, the code is filled with quite some require('utilities').debug('abc').
how to turn it off during the production since it will slow down my app a lot. I expect it is watching some global environment, but cannot find any doc.
/Eric
I don't think that there is a proper way of disabling util.debug output.
The best advice I can get you is to switch to debug module, written by TJ Holowaychuk.
Meanwhile, you may disable util.debug output in production simply by redefining it with an empty function, e.g.:
if (process.env.NODE_ENV === 'production') {
require('util').debug = function() {};
}
I would still recommend to put additional conditions into code for each debug output statement. Like
if (config.debug) { /* do debug output */ }
Overriding built-in function (as Leonid Beschastny suggested), in my opinion, is very bad idea and can lead to conflicts in third party modules.

How do you load data into an attributed database class generated by the MFC application wizard?

Using the MFCApplication wizard in Visual C++ 2012, if "Generate attributed database class" is checked, a header with some special syntax (attributed C++ classes) are generated, which look like this:
// MFCApplication2Set.h: interface of the CMFCApplication2Set class
//
#pragma once
// code generated on March-05-13, 9:26 AM
[
db_source(L"Provider=SQLNCLI11.1;..."),
db_table(L"dbo.tblEmployee")
]
class CMFCApplication2Set
{
public:
... big list of stuff that corresponds to the fields in your db table omitted ...
}
The above header corresponds to a mostly empty implementation file:
// MFCApplication2Set.cpp : implementation of the CMFCApplication2Set class
//
#include "stdafx.h"
#include "MFCApplication2.h"
#include "MFCApplication2Set.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFCApplication2Set implementation
That was the WHOLE implementation class. Notice that:
A. No parent class name is specified anywhere.
B. There's some "Visual C++ magic" going on here, that is, as a novice to modern C++, I'm lost.
db_source is documented here but the documentation is pretty thin or at least opaque to me.
Questions:
I was mystified by this syntax when I first saw it, but I figured out it's probably a variant of this Attributes feature in Visual C++. It is that, right?
How am I meant to I use these generated "attributed database class" objects? I found this documentation but if you look carefully at that documentation, that code sample is showing people the Old Way and the New Way, and is not telling me what I want to know which is how to use this new object that the IDE can not give me any documentation or code completion features for. Also since the generated code for the CMFCApplication2Set class generated by the wizard does not reference any types or class names, I'm lost. If I could even use some IDE feature to know what methods and stuff have been Magically Injected into this Magical mystery Object, I'd be better off. The only think I can think to do is to learn the old way and learn all the things you can call from the old two-separate-ATL-types world, and then somehow learn to combine them.
In a nutshell, I'm looking for the minimum syntax I need to know to actually use one of these Attributed Database Class instances, variables, as they are generated in a new MFC app by the wizard. The instance shown below is a member of an MFC document class and CMFCApplication2Set m_MFCApplication2Set is declared as a field inside the MFC document class.
What I have tried is to use this "untyped object". This object appears to have lots of data fields (m_X) and has only one method that shows up in IDE code completion, called GetRowSetProperties. Thanks to whatever magic or injection is going on, this generated Attributed Database Class (which does not visibly inherit anything) is a complete mystery to me at edit time and compile time.
Here's me just trying to inspect this thing to see if it even initialized itself when its constructor ran:
BOOL CMFCApplication2Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE;
TRACE( m_MFCApplication2Set.m_AStringFieldName); // outputs NOISE.
return TRUE; }
At compile time and edit time, the IDE gives me NO help about the types involved in this "anonymous" class that inherits from nothing, but which gets lots of secret powers due to some kind of Injection via those attributes I'm guessing. At debug time, I can see that there is more than just a bunch of data fields in this C++ class, but this still doesn't help me know how to use it. A minimal code sample of using one of these to go get a recordset from the database, would be great.
Update: Calling OpenDataSource is fun, because it compiles but the IDE doesn't think it should be valid. Nevertheless, it runs, and returns 0 as the result, but that doesn't actually initialize this CThingyThatVisualStudioGaveYouThatYouDontKnowWhatItIs:
This is a deprecated feature of attributed C++ code. Pre-processor expands code and replaces attributes with actual base classes. If you enable generation of these intermediate files, things are going to be more clear to you:
You will have XXX.mrg.cpp and XXX.mrg.h files generated, which you can review and see the real C++ code forwarded to compiler.
The attributes will be replaced with substituted bases classes, maps like BEGIN_COLUMN_MAP etc. The attributed source code is compact, but the feature is deprecated and looking into expanded code it should be easy (if necessary) to strip the attributes and copy expanded code right into source. It's easy with DB attributes, and more difficult with COM attributes since the internal dependencies are most sophisticated.

Visual C++ / STL exception not caught

The following method (in a Visual Studio 2008 ref class) contains a simple error that I thought would be caught - but instead it causes the process to abort with a "Debug Assertion Failed!" message box (msg includes the offending STL vector src line#). This occurs whether compiled in Debug or Release mode. The process in this case is Excel.exe and the method is accessed via COM interop.
Can someone tell me why this error doesn't get trapped ?
String^ FOO()
{
try {
std::vector<int> vfoo;
vfoo.push_back(999);
return vfoo[1].ToString(); //!!!! error: index 1 not valid
}
catch(std::exception& stdE) { // not catching
return "Unhandled STL exception";
}
catch(System::Exception^ E) { // not catching
return "Unhandled .NET exception: " + E->Message;
}
catch(...) { // not even this is catching
return "Unhandled exception";
}
}
In the Debug configuration you'll get an assert that's enabled by the iterator debugging feature. Designed to help to find mistakes in your use of the standard C++ library. You can use the Call Stack window to trace back to the statement in your code that triggered the assert. The feature is controlled by the _HAS_ITERATOR_DEBUGGING macro, very few reasons to ever turn that off in the Debug build. Well, none.
In the Release configuration, you'll run into the Checked Iterators feature, part of the Secure CRT Library initiative introduced at VS2005 and controlled by the _SECURE_SCL macro. It has a hook built in to get the debugger to stop, much as the above, to show you why it bombed. But not without a debugger, if none is attached then it immediately terminates your program with SEH exception code 0xc0000417. That's kinda where the buck stops, the DLL version of the CRT was built with _SECURE_SCL in effect and you have no option to not use that DLL when you write managed code. Building with /MT is required to completely turn it off and that's not possible in C++/CLI.
This tends to drive C++ programmers pretty nutty, catch (...) {} is a blessed language feature even though the odds of restoring program state are very close to zero. There is a back-door however (there's always a back-door), the argument validation code emits the error condition through a function pointer. The default handler immediately aborts the program with no way to catch it, not even with SetUnhandledExceptionFilter(). You can replace the handler with the _set_invalid_parameter_handler() function. That needs to be done by your Main() method, something like this:
#include "stdafx.h"
#include <stdlib.h>
using namespace System;
#pragma managed(push, off)
void no_invalid_parameter_exit(const wchar_t * expression, const wchar_t * function,
const wchar_t * file, unsigned int line, uintptr_t pReserved) {
throw new std::invalid_argument("invalid argument");
}
#pragma managed(pop)
int main(array<System::String ^> ^args)
{
_set_invalid_parameter_handler(no_invalid_parameter_exit);
// etc...
}
Which will run one of your catch handlers. The managed one, leaving no decent breadcrumbs to show what happened, but that's normal for native C++ exceptions.
"Debug Assertion Failed!" sounds like, well, an assert()-like check. These are NOT exceptions.
I actually use assert()-style checking for everything that constitutes a programming error, and use exceptions for runtime errors. Maybe Microsoft follows a similar policy; an "index out of bounds" is clearly a programming error, not something that is caused by e.g. your disk getting full.

Is there any fast tool which performs constant substitution without stripping out comments in JavaScript source code?

For example, setting MYCONST = true would lead to the transformation of
if (MYCONST) {
console.log('MYCONST IS TRUE!'); // print important message
}
to
if (true) {
console.log('MYCONST IS TRUE!'); // print important message
}
This tool ideally has a fast node.js accessible API.
A better way to achieve what you want -
Settings.js
settings = {
MYCONST = true
};
MainCode.js
if (settings.MYCONST) {
console.log('MYCONST IS TRUE!'); // print important message
}
This way, you make a change to one single file.
google's closure compiler does, among other things, inlining of constants when annotated as such, leaving string content untouched but I am not sure if it's a viable option for you.
Patch a beautifier, for example
Get the JS Beautifier https://raw.github.com/einars/js-beautify/master/beautify.js written in JS.
Replace the last line of function print_token() by something like
output.push(token_text=="MYCONST"?"true":token_text);
Call js_beautify(your_code) from within nodejs.
The Apache Ant build system supports a replace task that could be used to achieve this.
Edit: Whoops. Gotta read title first. Ignore me.
Google Closure Compiler has such a feature:
You can combine the #define tag in your code with the --define parameter to change variables at "compile" time.
The closure compiler will also remove your if-statement, which is probably what you want.
Simply write your code like this:
/** #define {boolean} */
var MYCONST = false; // default value is necessary here
if (MYCONST) {
console.log('MYCONST IS TRUE!'); // print important message
}
And call the compiler with the parameter:
java -jar closure-compiler.jar --define=MYCONST=true --js pathto/file.js
Regarding you API request: Closure Compiler has a JSON API.

Resources