why is code not executing on return from Future in Dart program - dart

Could someone please explain to me why in the following code (using r25630 Windows), the value of iInsertTot at line 241 is null, or more to the point, why is line 234 ("return iInsertTot;") not executed and therefore at line 241, iInsertTot is null. The value of iInsertTot at lines 231/232 is an integer. While I can and probably should code this differently, I thought that I would try and see if it worked, because my understanding of Futures and Chaining was that it would work. I have used “return” in a similar way before and it worked, but I was returning null in those cases (eg. line 201 below).
/// The problem lines are :
233 fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });
While running in the debugger, it appears that line 234 “return iInsertTot;” is never actually executed. Running from command line has the same result.
The method being called on line 233 (fUpdateTotalsTable) is something I am just in the process of adding, and it consists basically of sync code at this stage. However, the debugger appears to go through it correctly.
I have included the method “fUpdateTotalsTable()” (line 1076) just in case that is causing a problem.
Lines 236 to 245 have just been added, however just in case that code is invalid I have commented those lines out and run with the same problem occurring.
218 /*
219 * Process Inserts
220 */
221 }).then((_) {
222 sCheckpoint = "fProcessMainInserts";
223 ogPrintLine.fPrintForce ("Processing database ......");
224 int iMaxInserts = int.parse(lsInput[I_MAX_INSERTS]);
225 print ("");
226 return fProcessMainInserts(iMaxInserts, oStopwatch);
227 /*
228 * Update the 'totals' table with the value of Inserts
229 */
230 }).then((int iReturnVal) {
231 int iInsertTot = iReturnVal;
232 sCheckpoint = "fUpdateTotalsTable (insert value)";
233 fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });
236 /*
237 * Display totals for inserts
238 */
239 }).then((int iInsertTot) {
240 ogTotals.fPrintTotals(
241 "${iInsertTot} rows inserted - Inserts completed",
242 iInsertTot, oStopwatch.elapsedMilliseconds);
243
244 return null;
245 /*
192 /*
193 * Clear main table if selected
194 */
195 }).then((tReturnVal) {
196 if (tReturnVal)
197 ogPrintLine.fPrintForce("Random Keys Cleared");
198 sCheckpoint = "Clear Table ${S_TABLE_NAME}";
199 bool tClearTable = (lsInput[I_CLEAR_YN] == "y");
200 if (!tFirstInstance)
201 return null;
202 return fClearTable(tClearTable, S_TABLE_NAME);
203
204 /*
205 * Update control row to increment count of instances started
206 */
207 }).then((_) {
1073 /*
1074 * Update totals table with values from inserts and updates
1075 */
1076 async.Future<bool> fUpdateTotalsTable() {
1077 async.Completer<bool> oCompleter = new async.Completer<bool>();
1078
1079 String sCcyValue = ogCcy.fCcyIntToString(ogTotals.iTotAmt);
1080
1081 print ("\n********* Total = ${sCcyValue} \n");
1082
1083 oCompleter.complete(true);
1084 return oCompleter.future;
1085 }

Your function L230-235 does not return anything and that's why your iInsertTot is null L239. To make it work you have to add a return at line 233.
231 int iInsertTot = iReturnVal;
232 sCheckpoint = "fUpdateTotalsTable (insert value)";
233 return fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });

Related

Xtext cannot read javax.persistence.ManyTo*, OneTo* FetchType properly

I'm currently searching for a problem in one of our projects, which uses Xtext to generate java source code.
We use the model inferrer and Xannotation to use javax.* annotations to generate our entities.
import javax.persistence.FetchType
import javax.persistence.Id
import javax.persistence.Column
import javax.persistence.ManyToOne
package test.some.namespace {
domain DomainA {
entity for table "DOMAINA" {
#Id
#Column(name = "DAIA", unique = true)
Long id;
}
}
domain DomainB {
entity for table "DOMAINB" {
#Id
#Column(name = "DAIB", unique = true)
Long id;
#ManyToOne(fetch = FetchType::LAZY)
DomainA domainA;
}
}
domain DomainC {
entity for table "DOMAINC" {
#Id
#Column(name = "DAIC", unique = true)
Long id;
#ManyToOne(fetch = FetchType::LAZY)
DomainA domainA;
}
}
}
We search for the annotation by iterating through XAnnotationElementValuePair pair : annotation.getElementValuePairs() and return the value pair.getValue(), so far it works.
Now we try to access the FetchType with (exp as XMemberFeatureCall).feature where exp is the result of pair.getValue().
For DomainB.domainA it will return an instance of org.eclipse.xtext.common.types.impl.JvmEnumerationLiteralImplCustom.
For DomainC.domainA it will return an instance of org.eclipse.xtext.common.types.impl.JvmVoidImplCustom.
This problem only occurs when I save the document. This is the current thread stack from eclipse.
Thread [Worker-5] (Suspended (breakpoint at line 60 in CustomDSLJvmModelInferrer$2))
owns: ClusteringBuilderState (id=19135)
CustomDSLJvmModelInferrer.xtend line: 60
JvmDispatchableModelAssociator.installDerivedState(DerivedStateAwareResource, boolean) line: 66
BatchLinkableResource(DerivedStateAwareResource).installDerivedState(boolean) line: 159
DerivedStateAwareResourceDescriptionManager.internalGetResourceDescription(Resource, IDefaultResourceDescriptionStrategy) line: 53
DefaultResourceDescriptionManager$1.get() line: 60
DefaultResourceDescriptionManager$1.get() line: 1
OnChangeEvictingCache.get(Object, Resource, Provider<T>) line: 75
DerivedStateAwareResourceDescriptionManager(DefaultResourceDescriptionManager).getResourceDescription(Resource) line: 58
ClusteringBuilderState.writeNewResourceDescriptions(BuildData, IResourceDescriptions, CurrentDescriptions, IProgressMonitor) line: 366
ClusteringBuilderState.doUpdate(BuildData, ResourceDescriptionsData, IProgressMonitor) line: 121
ClusteringBuilderState(AbstractBuilderState).update(BuildData, IProgressMonitor) line: 112
XtextBuilder.doBuild(ToBeBuilt, IProgressMonitor, IXtextBuilderParticipant$BuildType) line: 194
XtextBuilder.incrementalBuild(IResourceDelta, IProgressMonitor) line: 171
XtextBuilder.build(int, Map, IProgressMonitor) line: 99
BuildManager$2.run() line: 734
SafeRunner.run(ISafeRunnable) line: 42
BuildManager.basicBuild(int, IncrementalProjectBuilder, Map<String,String>, MultiStatus, IProgressMonitor) line: 206
BuildManager.basicBuild(IBuildConfiguration, int, IBuildContext, ICommand[], MultiStatus, IProgressMonitor) line: 246
BuildManager$1.run() line: 299
SafeRunner.run(ISafeRunnable) line: 42
BuildManager.basicBuild(IBuildConfiguration, int, IBuildContext, MultiStatus, IProgressMonitor) line: 302
BuildManager.basicBuildLoop(IBuildConfiguration[], IBuildConfiguration[], int, MultiStatus, IProgressMonitor) line: 358
BuildManager.build(IBuildConfiguration[], IBuildConfiguration[], int, IProgressMonitor) line: 381
AutoBuildJob.doBuild(IProgressMonitor) line: 143
AutoBuildJob.run(IProgressMonitor) line: 241
Worker.run() line: 54
But it works fine if I just modify the document without saving. Stack from eclipse:
Thread [Worker-3] (Suspended (breakpoint at line 60 in CustomDSLJvmModelInferrer$2))
owns: DirtyStateManager (id=19093)
owns: Object (id=19094)
CustomDSLJvmModelInferrer.xtend line: 60
JvmDispatchableModelAssociator.installDerivedState(DerivedStateAwareResource, boolean) line: 66
BatchLinkableResource(DerivedStateAwareResource).installDerivedState(boolean) line: 159
DirtyStateResourceDescription$Manager.getResourceDescription(Resource) line: 65
DirtyStateEditorSupport.announceDirtyState(XtextResource) line: 467
XtextDocumentReconcileStrategy.postParse(XtextResource, IProgressMonitor) line: 160
XtextDocumentReconcileStrategy.doReconcile(IRegion) line: 146
XtextDocumentReconcileStrategy.reconcile(IRegion) line: 65
XtextReconciler.doRun(XtextResource, IProgressMonitor) line: 401
XtextReconciler.access$3(XtextReconciler, XtextResource, IProgressMonitor) line: 386
XtextReconciler$1.process(XtextResource) line: 327
XtextReconciler$1.process(Object) line: 1
XtextReconciler$1(IUnitOfWork$Void).exec(T) line: 36
XtextDocument$XtextDocumentLocker.modify(IUnitOfWork<T,XtextResource>) line: 418
XtextDocument.internalModify(IUnitOfWork<T,XtextResource>) line: 131
XtextReconciler.run(IProgressMonitor) line: 324
Worker.run() line: 54
So far I am all out of ideas. Is it a bug? Is there something i missed?
I hope you guys can help me.
Best regards

Remote Connection like Browser Toolbox

I'm trying to interact with another open profile, which is a seperate process. Browser Toolbox does this. I was wondering how can I re-simulate this behavior? Without the prompt asking for "allow remote connection"?
My goal is to (1) find all open firefox process, (2) access each of its xpcom and figure out the profile name, (3) and if its a profile name Im interested in, Ill focus its most recent window.
I don't know but I'm getting somewhere by tracing it in MXR:
http://mxr.mozilla.org/mozilla-release/source/browser/devtools/framework/toolbox-process-window.js#11
11 let { debuggerSocketConnect, DebuggerClient } =
12 Cu.import("resource://gre/modules/devtools/dbg-client.jsm", {});
13 let { ViewHelpers } =
14 Cu.import("resource:///modules/devtools/ViewHelpers.jsm", {});
15
16 /**
17 * Shortcuts for accessing various debugger preferences.
18 */
19 let Prefs = new ViewHelpers.Prefs("devtools.debugger", {
20 chromeDebuggingHost: ["Char", "chrome-debugging-host"],
21 chromeDebuggingPort: ["Int", "chrome-debugging-port"]
22 });
23
24 let gToolbox, gClient;
25
26 function connect() {
27 window.removeEventListener("load", connect);
28 // Initiate the connection
29 let transport = debuggerSocketConnect(
30 Prefs.chromeDebuggingHost,
31 Prefs.chromeDebuggingPort
32 );
33 gClient = new DebuggerClient(transport);
34 gClient.connect(() => {
35 let addonID = getParameterByName("addonID");
36
37 if (addonID) {
38 gClient.listAddons(({addons}) => {
39 let addonActor = addons.filter(addon => addon.id === addonID).pop();
40 openToolbox({ addonActor: addonActor.actor, title: addonActor.name });
41 });
42 } else {
43 gClient.listTabs(openToolbox);
44 }
45 });
46 }
47
I ran the profile and it looks like the pref ..-host is localhost and ..-port is 6080. I'm not sure how this helps target a specific profile though. Maybe on start of the browser toolbox it opened port 6080 to the opener profile. I'm not sure, but if its true, then you'll have to run code from within the target profile to open a port maybe.
Totally not sure though.
But port is opened here:
http://mxr.mozilla.org/mozilla-release/source/browser/devtools/framework/ToolboxProcess.jsm#107
106
107 BrowserToolboxProcess.prototype = {
108 /**
109 * Initializes the debugger server.
110 */
111 _initServer: function() {
112 dumpn("Initializing the chrome toolbox server.");
113
114 if (!this.loader) {
115 // Create a separate loader instance, so that we can be sure to receive a
116 // separate instance of the DebuggingServer from the rest of the devtools.
117 // This allows us to safely use the tools against even the actors and
118 // DebuggingServer itself, especially since we can mark this loader as
119 // invisible to the debugger (unlike the usual loader settings).
120 this.loader = new DevToolsLoader();
121 this.loader.invisibleToDebugger = true;
122 this.loader.main("devtools/server/main");
123 this.debuggerServer = this.loader.DebuggerServer;
124 dumpn("Created a separate loader instance for the DebuggerServer.");
125
126 // Forward interesting events.
127 this.debuggerServer.on("connectionchange", this.emit.bind(this));
128 }
129
130 if (!this.debuggerServer.initialized) {
131 this.debuggerServer.init();
132 this.debuggerServer.addBrowserActors();
133 dumpn("initialized and added the browser actors for the DebuggerServer.");
134 }
135
136 this.debuggerServer.openListener(Prefs.chromeDebuggingPort);
137
138 dumpn("Finished initializing the chrome toolbox server.");
139 dumpn("Started listening on port: " + Prefs.chromeDebuggingPort);
140 },
141

neo4django with Neo4j 2.0

I'm just starting out using Neo4j and I'd like to use 2.0 (I have 2.0.1 community installed). I see that neo4django was only tested against neo4j 1.8.2-1.9.4, but have people gotten it working with 2.x? I installed the gremlin plugin but can't create or query through neo4django.
create:
In [8]: NeoProfile.objects.create(profile_id=1234)
[INFO] requests.packages.urllib3.connectionpool#214: Resetting dropped connection: localhost
---------------------------------------------------------------------------
StatusException Traceback (most recent call last)
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 NeoProfile.objects.create(profile_id=1234)
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/manager.pyc in create(self, **kwargs)
41
42 def create(self, **kwargs):
---> 43 return self.get_query_set().create(**kwargs)
44
45 def filter(self, *args, **kwargs):
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/query.pyc in create(self, **kwargs)
1295 if 'id' in kwargs or 'pk' in kwargs:
1296 raise FieldError("Neo4j doesn't allow node ids to be assigned.")
-> 1297 return super(NodeQuerySet, self).create(**kwargs)
1298
1299 #TODO would be awesome if this were transactional
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/db/models/query.pyc in create(self, **kwargs)
375 obj = self.model(**kwargs)
376 self._for_write = True
--> 377 obj.save(force_insert=True, using=self.db)
378 return obj
379
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in save(self, using, **kwargs)
315
316 def save(self, using=DEFAULT_DB_ALIAS, **kwargs):
--> 317 return super(NodeModel, self).save(using=using, **kwargs)
318
319 #alters_data
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using)
461 if force_insert and force_update:
462 raise ValueError("Cannot force both insert and updating in model saving.")
--> 463 self.save_base(using=using, force_insert=force_insert, force_update=force_update)
464
465 save.alters_data = True
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using, *args, **kwargs)
331
332 is_new = self.id is None
--> 333 self._save_neo4j_node(using)
334 self._save_properties(self, self.__node, is_new)
335 self._save_neo4j_relationships(self, self.__node)
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in _save_neo4j_node(self, using)
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in trans_method(func, *args, **kw)
95 #TODO this is where generalized transaction support will go,
96 #when it's ready in neo4jrestclient
---> 97 ret = func(*args, **kw)
98 #tx.commit()
99 return ret
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in _save_neo4j_node(self, using)
359 self.__node = conn.gremlin_tx(script, types=type_hier_props,
360 indexName=self.index_name(),
--> 361 typesToIndex=type_names_to_index)
362 return self.__node
363
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/neo4jclient.pyc in gremlin_tx(self, script, **params)
177 will be wrapped in a transaction.
178 """
--> 179 return self.gremlin(script, tx=True, **params)
180
181 def cypher(self, query, **params):
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/neo4jclient.pyc in gremlin(self, script, tx, raw, **params)
166 try:
167 return send_script(include_unloaded_libraries(lib_script),
--> 168 params)
169 except LibraryCouldNotLoad:
170 if i == 0:
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/neo4jclient.pyc in send_script(s, params)
151 if raw:
152 execute_kwargs['returns'] = RETURNS_RAW
--> 153 script_rv = ext.execute_script(s, params=params, **execute_kwargs)
154 if isinstance(script_rv, basestring):
155 if LIBRARY_ERROR_REGEX.match(script_rv):
/Users/atomos/workspace/Project-Vitamin/src/neo4j-rest-client/neo4jrestclient/client.py in __call__(self, *args, **kwargs)
2313 except (ValueError, AttributeError, KeyError, TypeError):
2314 pass
-> 2315 raise StatusException(response.status_code, msg)
2316
2317 def __repr__(self):
StatusException: Code [400]: Bad Request. Bad request syntax or unsupported method.
Invalid data sent: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: groovy.lang.MissingMethodException.setMaxBufferSize() is applicable for argument types: () values: []
query:
In [9]: NeoProfile.objects.filter(profile_id=1234)
Out[9]: ---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 NeoProfile.objects.filter(profile_id=1234)
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/core/displayhook.pyc in __call__(self, result)
236 self.start_displayhook()
237 self.write_output_prompt()
--> 238 format_dict = self.compute_format_data(result)
239 self.write_format_data(format_dict)
240 self.update_user_ns(result)
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/core/displayhook.pyc in compute_format_data(self, result)
148 MIME type representation of the object.
149 """
--> 150 return self.shell.display_formatter.format(result)
151
152 def write_format_data(self, format_dict):
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/core/formatters.pyc in format(self, obj, include, exclude)
124 continue
125 try:
--> 126 data = formatter(obj)
127 except:
128 # FIXME: log the exception
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
445 type_pprinters=self.type_printers,
446 deferred_pprinters=self.deferred_printers)
--> 447 printer.pretty(obj)
448 printer.flush()
449 return stream.getvalue()
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/lib/pretty.pyc in pretty(self, obj)
358 if callable(meth):
359 return meth(obj, self, cycle)
--> 360 return _default_pprint(obj, self, cycle)
361 finally:
362 self.end_group()
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _default_pprint(obj, p, cycle)
478 if getattr(klass, '__repr__', None) not in _baseclass_reprs:
479 # A user-provided repr.
--> 480 p.text(repr(obj))
481 return
482 p.begin_group(1, '<')
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/db/models/query.pyc in __repr__(self)
70
71 def __repr__(self):
---> 72 data = list(self[:REPR_OUTPUT_SIZE + 1])
73 if len(data) > REPR_OUTPUT_SIZE:
74 data[-1] = "...(remaining elements truncated)..."
/Users/atomos/workspace/Project-Vitamin/lib/python2.7/site-packages/django/db/models/query.pyc in __len__(self)
85 self._result_cache = list(self.iterator())
86 elif self._iter:
---> 87 self._result_cache.extend(self._iter)
88 if self._prefetch_related_lookups and not self._prefetch_done:
89 self._prefetch_related_objects()
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/query.pyc in iterator(self)
1274 using = self.db
1275 if not self.query.can_filter():
-> 1276 for model in self.query.execute(using):
1277 yield model
1278 else:
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/query.pyc in execute(self, using)
1161 conn = connections[using]
1162
-> 1163 groovy, params = self.as_groovy(using)
1164
1165 raw_result_set = conn.gremlin_tx(groovy, **params) if groovy is not None else []
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/query.pyc in as_groovy(self, using)
925 # add the typeNodeId param, either for type verification or initial
926 # type tree traversal
--> 927 cypher_params['typeNodeId'] = self.model._type_node(using).id
928
929 type_restriction_expr = """
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in _type_node(cls, using)
411 return cls.__type_node_memoized(using)
412 else:
--> 413 return cls.__type_node_classmethod(using)
414
415 #classmethod
/Users/atomos/workspace/Project-Vitamin/src/neo4django/neo4django/db/models/base.pyc in __type_node(cls, using)
394 script_rv = conn.gremlin_tx(script, types=type_hier_props)
395 except Exception, e:
--> 396 raise RuntimeError(error_message, e)
397 if not hasattr(script_rv, 'properties'):
398 raise RuntimeError(error_message + '\n\n%s' % script_rv)
RuntimeError: ('The type node for class NeoProfile could not be created in the database.', StatusException())
My model is incredibly complex:
class NeoProfile(neomodels.NodeModel):
profile_id = neomodels.IntegerProperty(indexed=True)

why when exiting a Dart async Future is the following error not being caught (correctly)?

I have a problem using Dart postgresql database driver (xxgreg on Github) insofar as when the postgresql server is not running and it needs to be, I am unable to correctly handle the error. I’ve attempted to solve this for a while now, so any help would be appreciated. I can easily work around it by handling it silently and simply testing if the database connection object is null, however I think it should be possible to handle the raising of an error. It should be noted that when the Postgresql server is running, there is no problem.
The error that I am getting is as follows :
“Uncaught Error: Exception: fConnectToDb: Database is not connected
Stack Trace: ………….”
The problem area relates to these lines of code : (Line 663 is called from line 169 below)
663 async.Future<bool> fConnectToDb(String sUri) {
664 async.Completer<bool> oCompleter = new async.Completer<bool>();
665
666 pg.connect(sUri)
667 .catchError((oError) {
668 String sErrorMsg = (oError is SocketException) ?
669 "Database is not connected"
670 : "Fatal error encountered ${oError}";
671 throw("fConnectToDb: ${sErrorMsg}");
//(expanded below)
I have previously encountered problems in this area where at line 671, instead of throwing an exception, I called an internal method which displayed an error, and terminated the program. I found however what appeared to be a problem doing that, and I found in that situation, throwing an error enabled the program to exit the Future method, and not doing that appeared to be the problem. The problem may relate to the Future not being completed, but I don’t know how to do that and also throw an exception.
The overall code in-question is as follows. I put a try at line 167… 406, however that doesn’t catch the error either.
164 /*
165 * Connect to database
166 */
167 try {
168 sCheckpoint = "Connect to Database";
169 fConnectToDb(sUri)
170 .catchError((oError) =>
171 fFatal(sCheckpoint, "Error = \n${oError}"))
172 .then((_) {
173 if (ogDb == null) // ogDb is global object for db connection
174 fFatal(sCheckpoint, "Database did not connect");
175
176 /*
177 * Perform an SQL Select to test connection
178 */
179 ogPrintLine.fPrintForce("Testing Db connection .....");
180 sCheckpoint = "test connection";
181 return fProcessSqlSelect ("SELECT count(*) FROM ${S_TABLE_NAME}",
182 false);
183 }).then((llResult) {
184
…………
…………
// (catch related to line 167)
406 } catch(oError) {fFatal("Program Main()",
407 "Checkpoint ${sCheckpoint}, Error = \n${oError}");}
408 }
………..
………..
660 /*
661 * Connect To Database
662 */
663 async.Future<bool> fConnectToDb(String sUri) {
664 async.Completer<bool> oCompleter = new async.Completer<bool>();
665
666 pg.connect(sUri)
667 .catchError((oError) {
668 String sErrorMsg = (oError is SocketException) ?
669 "Database is not connected"
670 : "Fatal error encountered ${oError}";
671 throw("fConnectToDb: ${sErrorMsg}");
672
673 }).then((pg.Connection oDb) {
674 ogDb = oDb;
675 oCompleter.complete(true);
676 return;
677
678 });
679
680 return oCompleter.future;
681 }
As far as I can determine, it appears to me that it's Ok to throw an error in a Future providing it's followed by a catchError() that doesn't throw an error.
The following code appears to solve the problem that I was having :
/*
* Connect To Database
*/
async.Future<bool> fConnectToDb(String sUri) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
pg.connect(sUri).then((pg.Connection oDb) {
ogDb = oDb; // assign to global database object
oCompleter.complete(true);
return;
}).catchError((oError) =>
fFatal("fConnectToDb", "Error=\n${oError}"));
return oCompleter.future;
}

Using yyparse() to make a two pass assembler?

I'm writing an assembler for a custom micro controller I'm working on. I've got the assembler to a point where it will assemble instructions down to binary.
However, I'm now having problems with getting labels to work. Currently, when my assembler encounters a new label, it stores the name of the label and the memory location its referring to. When an instruction references a label, the assembler looks up the label and replaces the label with the appropriate value.
This is fine and dandy, but what if the label is defined after the instruction referencing it? Because of this, I need to have my parser run over the code twice.
Here's what I currently have for my main function:
303 int main(int argc, char* argv[])
304 {
305
306 if(argc < 1 || strcmp(argv[1],"-h")==0 || 0==strcmp(argv[1],"--help"))
307 {
308 //printf("%s\n", usage);
309 return 1;
310 }
311 // redirect stdin to the file pointer
312 int stdin = dup(0);
313 close(0);
314
315 // pass 1 on the file
316 int fp = open(argv[1], O_RDONLY, "r");
317 dup2(fp, 0);
318
319 yyparse();
320
321 lseek(fp, SEEK_SET, 0);
322
323 // pass 2 on the file
324 if(secondPassNeeded)
325 {
326 fp = open(argv[1], O_RDONLY, "r");
327 dup2(fp, 0);
328 yyparse();
329 }
330 close(fp);
331
332 // restore stdin
333 dup2(0, stdin);
334
335 for(int i = 0; i < labels.size(); i++)
336 {
337 printf("Label: %s, Loc: %d\n", labels[i].name.c_str(), labels[i].memoryLoc);
338 }
339 return 0;
340 }
I'm using this inside a flex/bison configuration.
If that is all you need, you don't need a full two-pass assembler. If the label is not defined when you reference it, you simply output a stand-in address (say 0x0000) and have a data structure that lists all of the places with forward references and what symbol they refered to. At the end of the file (or block if you have local symbols), you simply go through that list and patch the addresses.

Resources