Skip to content

Commit

Permalink
Remove createChild argument from jsvFindChildFromString, add jsvFindO…
Browse files Browse the repository at this point in the history
…rAddChildFromString instead
  • Loading branch information
gfwilliams committed Oct 6, 2023
1 parent 00b0501 commit f6894cd
Show file tree
Hide file tree
Showing 19 changed files with 94 additions and 88 deletions.
1 change: 1 addition & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Tidying up error messages (no trailing '.' or '\n'), making almost-similar error messages the same
Fix issue using `String.concat` with flash strings (fix #2268)
jsvFindChildFromString enhancement - adds 10% performance on minified code
Remove createChild argument from jsvFindChildFromString, add jsvFindOrAddChildFromString instead

2v19 : Fix Object.values/entries for numeric keys after 2v18 regression (fix #2375)
nRF52: for SD>5 use static buffers for advertising and scan response data (#2367)
Expand Down
6 changes: 3 additions & 3 deletions libs/filesystem/jswrap_file.c
Original file line number Diff line number Diff line change
Expand Up @@ -636,17 +636,17 @@ int jswrap_E_flashFatFS(JsVar* options) {
uint16_t sectors = FS_SECTOR_COUNT;
uint8_t format = 0;
if (jsvIsObject(options)) {
JsVar *a = jsvObjectGetChild(options, "addr", false);
JsVar *a = jsvObjectGetChildIfExists(options, "addr");
if (a) {
if (jsvIsNumeric(a) && jsvGetInteger(a)>0x100000)
addr = (uint32_t)jsvGetInteger(a);
}
JsVar *s = jsvObjectGetChild(options, "sectors", false);
JsVar *s = jsvObjectGetChildIfExists(options, "sectors");
if (s) {
if (jsvIsNumeric(s) && jsvGetInteger(s)>0)
sectors = (uint16_t)jsvGetInteger(s);
}
JsVar *f = jsvObjectGetChild(options, "format", false);
JsVar *f = jsvObjectGetChildIfExists(options, "format");
if (f) {
if (jsvIsBoolean(f))
format = jsvGetBool(f);
Expand Down
4 changes: 2 additions & 2 deletions libs/graphics/graphics.c
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ bool graphicsGetFromVar(JsGraphics *gfx, JsVar *parent) {

// Set the data variable for graphics - called initially when a graphics instance is first make
void graphicsSetVarInitial(JsGraphics *gfx) {
JsVar *dataname = jsvFindChildFromString(gfx->graphicsVar, JS_HIDDEN_CHAR_STR"gfx", true);
JsVar *dataname = jsvFindOrAddChildFromString(gfx->graphicsVar, JS_HIDDEN_CHAR_STR"gfx");
JsVar *data = jsvSkipName(dataname);
if (!data) {
data = jsvNewStringOfLength(sizeof(JsGraphicsData), NULL);
Expand All @@ -240,7 +240,7 @@ void graphicsSetVarInitial(JsGraphics *gfx) {

// Set the data variable for graphics - graphics data must exist
void graphicsSetVar(JsGraphics *gfx) {
JsVar *data = jsvSkipNameAndUnLock(jsvFindChildFromString(gfx->graphicsVar, JS_HIDDEN_CHAR_STR"gfx", false));
JsVar *data = jsvSkipNameAndUnLock(jsvFindChildFromString(gfx->graphicsVar, JS_HIDDEN_CHAR_STR"gfx"));
#if ESPR_GRAPHICS_INTERNAL
if (!data) {
graphicsInternal = *gfx;
Expand Down
14 changes: 7 additions & 7 deletions libs/network/socketserver.c
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ void _socketConnectionKill(JsNetwork *net, JsVar *connection) {
}

bool _socketConnectionOpen(JsVar *connection) {
return !(jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CLOSENOW, false)) ||
jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CLOSE, false)));
return !(jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CLOSENOW)) ||
jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CLOSE)));
}

// -----------------------------
Expand Down Expand Up @@ -505,7 +505,7 @@ bool socketServerConnectionsIdle(JsNetwork *net) {
JsVar *socket = isHttp ? jsvObjectGetChildIfExists(connection,HTTP_NAME_RESPONSE_VAR) : jsvLockAgain(connection);

int sckt = (int)jsvGetIntegerAndUnLock(jsvObjectGetChildIfExists(connection,HTTP_NAME_SOCKET))-1; // so -1 if undefined
bool closeConnectionNow = jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CLOSENOW, false));
bool closeConnectionNow = jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CLOSENOW));
int error = 0;

if (!closeConnectionNow) {
Expand Down Expand Up @@ -624,8 +624,8 @@ bool socketClientConnectionsIdle(JsNetwork *net) {

bool hadHeaders = false;
int error = 0; // error code received from netXxxx functions
bool closeConnectionNow = jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CLOSENOW, false));
bool alreadyConnected = jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CONNECTED, false));
bool closeConnectionNow = jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CLOSENOW));
bool alreadyConnected = jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CONNECTED));
int sckt = (int)jsvGetIntegerAndUnLock(jsvObjectGetChildIfExists(connection,HTTP_NAME_SOCKET))-1; // so -1 if undefined
if (sckt>=0) {
if (isHttp)
Expand Down Expand Up @@ -660,7 +660,7 @@ bool socketClientConnectionsIdle(JsNetwork *net) {
jsvObjectSetChild(connection, HTTP_NAME_SEND_DATA, sendData); // socketSendData updated sendData
} else {
// no data to send, do we want to close? do so.
if (jsvGetBoolAndUnLock(jsvObjectGetChild(connection, HTTP_NAME_CLOSE, false)))
if (jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(connection, HTTP_NAME_CLOSE)))
closeConnectionNow = true;
if (isHttp) {
JsVarInt contentToReceive = jsvGetIntegerAndUnLock(jsvObjectGetChildIfExists(socket, HTTP_NAME_RECEIVE_COUNT));
Expand Down Expand Up @@ -864,7 +864,7 @@ void serverListen(JsNetwork *net, JsVar *server, unsigned short port, SocketType
if (!arr) return; // out of memory

jsvObjectSetChildAndUnLock(server, HTTP_NAME_PORT, jsvNewFromInteger(port));
JsVar *options = jsvObjectGetChild(server, HTTP_NAME_OPTIONS_VAR, false);
JsVar *options = jsvObjectGetChildIfExists(server, HTTP_NAME_OPTIONS_VAR);

int sckt = netCreateSocket(net, socketType, 0/*server*/, port, options);
if (sckt<0) {
Expand Down
22 changes: 11 additions & 11 deletions scripts/build_jswrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
print(" path/to/modulename.js ; include a JS module called modulename")
print(" modulename:path/to/modulesource.js ; include a JS module called modulename")
print(" _:bootcode ; JS code to be executed at boot time")
print(" ; These can be specified in the JSMODULESOURCES environment variable")
print(" ; These can be specified in the JSMODULESOURCES environment variable")
exit(1)

boardName = sys.argv[len(sys.argv)-2]
Expand Down Expand Up @@ -262,7 +262,7 @@ def removeBlacklistForWrapper(blacklistfile,datas):
if black["name"] == "*":
toremove.append(idx)
print("Removing "+black["class"]+" due to blacklist wildcard")

# end extension by jumjum
return delete_by_indices( datas, toremove)
# ------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -329,7 +329,7 @@ def removeBlacklistForWrapper(blacklistfile,datas):
for jsondata in jsondatas:
# Include 'inline' C declarations
if ("generate_full" in jsondata) or (jsondata["type"]=="object"):
gen_name = "gen_jswrap"
gen_name = "gen_jswrap"
if "class" in jsondata: gen_name = gen_name + "_" + jsondata["class"];
gen_name = gen_name + "_" + jsondata["name"];
jsondata["generate"] = gen_name
Expand All @@ -355,18 +355,18 @@ def removeBlacklistForWrapper(blacklistfile,datas):
codeOut('');
# Include JavaScript functions
if ("generate_js" in jsondata):
gen_name = "gen_jswrap"
gen_name = "gen_jswrap"
if "class" in jsondata: gen_name = gen_name + "_" + jsondata["class"];
gen_name = gen_name + "_" + jsondata["name"];
jsondata["generate"] = gen_name

s = [ ]
params = getParams(jsondata)
result = getResult(jsondata)
if hasThis(jsondata): s.append("JsVar *parent")
for param in params:
if param[1]!="JsVar": FATAL_ERROR("All arguments to generate_js must be JsVars");
s.append(toCType(param[1])+" "+param[0]);
s.append(toCType(param[1])+" "+param[0]);

js = "";
with open(basedir+jsondata["generate_js"], 'r') as file:
Expand Down Expand Up @@ -399,7 +399,7 @@ def removeBlacklistForWrapper(blacklistfile,datas):
codeOut('');


# In jswBinarySearch we used to use READ_FLASH_UINT16 for sym->strOffset and sym->functionSpec for ESP8266
# In jswBinarySearch we used to use READ_FLASH_UINT16 for sym->strOffset and sym->functionSpec for ESP8266
# (where unaligned reads broke) but despite being packed, the structure JswSymPtr is still always an multiple
# of 2 in length so they will always be halfword aligned.
codeOut("""
Expand All @@ -409,7 +409,7 @@ def removeBlacklistForWrapper(blacklistfile,datas):
uint8_t symbolCount = READ_FLASH_UINT8(&symbolsPtr->symbolCount);
int searchMin = 0;
int searchMax = symbolCount - 1;
while (searchMin <= searchMax) {
while (searchMin <= searchMax) {
int idx = (searchMin+searchMax) >> 1;
const JswSymPtr *sym = &symbolsPtr->symbols[idx];
int cmp = FLASH_STRCMP(name, &symbolsPtr->symbolChars[sym->strOffset]);
Expand Down Expand Up @@ -535,8 +535,8 @@ def removeBlacklistForWrapper(blacklistfile,datas):
codeOut(' if (v) return v;');
codeOut(" }")
codeOut(' // ------------------------------------------ INSTANCE METHODS WE MUST CHECK CONSTRUCTOR FOR')
codeOut(' JsVar *proto = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_INHERITS_VAR, false)):0;')
codeOut(' JsVar *constructor = jsvIsObject(proto)?jsvSkipNameAndUnLock(jsvFindChildFromString(proto, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
codeOut(' JsVar *proto = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_INHERITS_VAR)):0;')
codeOut(' JsVar *constructor = jsvIsObject(proto)?jsvSkipNameAndUnLock(jsvFindChildFromString(proto, JSPARSE_CONSTRUCTOR_VAR)):0;')
codeOut(' jsvUnLock(proto);')
codeOut(' if (constructor && jsvIsNativeFunction(constructor)) {')
codeOut(' const JswSymList *l = jswGetSymbolListForConstructorProto(constructor);')
Expand Down Expand Up @@ -601,7 +601,7 @@ def removeBlacklistForWrapper(blacklistfile,datas):

codeOut(" if ("+check+") return &jswSymbolTables["+builtin["indexName"]+"];");
codeOut(' }')
codeOut(' JsVar *constructor = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
codeOut(' JsVar *constructor = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR)):0;')
codeOut(' if (constructor && jsvIsNativeFunction(constructor)) {')
codeOut(' const JswSymList *l = jswGetSymbolListForConstructorProto(constructor);')
codeOut(' jsvUnLock(constructor);')
Expand Down
38 changes: 19 additions & 19 deletions scripts/build_jswrapper_efficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def addToTree(tree, name, jsondata):
if len(name)==0:
if "" in tree: tree[""].append(jsondata)
else: tree[""] = [ jsondata ]
else:
else:
firstchar = name[:1]
if not firstchar in tree: tree[firstchar] = {}
addToTree(tree[firstchar], name[1:], jsondata)
Expand Down Expand Up @@ -69,7 +69,7 @@ def getTestFor(className, static):
#for ch in className:
# checkOffsets.append(n)
# checkCharacters.append(ch)
# n = n + 1
# n = n + 1
#checkOffsets.append(n)
#checkCharacters.append("\\0")
#return createStringCompare("parent->varData.str", checkOffsets, checkCharacters)
Expand All @@ -91,7 +91,7 @@ def getTestFor(className, static):
#for ch in className:
# checkOffsets.append(n)
# checkCharacters.append(ch)
# n = n + 1
# n = n + 1
#checkOffsets.append(n)
#checkCharacters.append("\\0")
# return createStringCompare("constructorName->varData.str", checkOffsets, checkCharacters)
Expand All @@ -111,11 +111,11 @@ def getTestFor(className, static):
#tree = sorted(tree, key=common.get_name_or_space)
# ------------------------------------------------------------------------------------------------------
#print json.dumps(tree, sort_keys=True, indent=2)
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
print("Outputting decision tree")
wrapperFile = open('src/jswrapper.c', 'w')

def codeOut(s):
def codeOut(s):
# print str(s)
wrapperFile.write(s+"\n");

Expand Down Expand Up @@ -157,17 +157,17 @@ def codeOutFunction(indent, func):
argNames = ["a","b","c","d"];
params = []
if "params" in func: params = func["params"]
if len(params)==0:
if len(params)==0:
if func["type"]=="variable" or common.is_property(func):
codeOut(indent+"jspParseVariableName();")
else:
codeOut(indent+"jspParseEmptyFunction();")
elif len(params)==1 and params[0][1]!="JsVarName":
elif len(params)==1 and params[0][1]!="JsVarName":
codeOut(indent+"JsVar *"+params[0][0]+" = jspParseSingleFunction();")
elif len(params)<9:
funcName = "jspParseFunction8"
paramCount = 8
if len(params)<5:
if len(params)<5:
funcName = "jspParseFunction"
paramCount = 4
paramDefs = []
Expand All @@ -188,7 +188,7 @@ def codeOutFunction(indent, func):
exit(1)
if "generate" in func:
commandargs = [];
if hasThis:
if hasThis:
commandargs.append("parent")
if "needs_parentName" in func:
commandargs.append("parentName")
Expand All @@ -198,10 +198,10 @@ def codeOutFunction(indent, func):
else:
commandargs.append(getUnLockGetter(param[1], param[0], func["name"]));
command = func["generate"]+"("+ ', '.join(commandargs) +")";
else:
else:
command = func["generate_full"];
if "return" in func:

if "return" in func:
codeOut(indent+"JsVar *_r = " + getCreator(func["return"][0], command, func["name"])+";");
else:
codeOut(indent+command+";");
Expand All @@ -211,7 +211,7 @@ def codeOutFunction(indent, func):
if "generate_full" in func or param[1]=="JsVar" or param[1]=="JsVarName":
codeOut(indent+"jsvUnLock("+param[0]+");");

if "return" in func:
if "return" in func:
codeOut(indent+"return _r;");
else:
codeOut(indent+"return 0;");
Expand Down Expand Up @@ -242,12 +242,12 @@ def codeOutTree(indent, tree, offset):
while len(charTree)==1 and char!='':
charOffset = charOffset + 1
char = charTree.keys()[0]
charTree = charTree[char]
charTree = charTree[char]
checkOffsets.append(charOffset)
if char=='': checkCharacters.append('\\0')
else: checkCharacters.append(char)
line = line + "if (" + createStringCompare("name", checkOffsets, checkCharacters) + ") {"
codeOut(line)
codeOut(line)
if char=='':
# charTree is now a list of possible functions
codeOutFunctionList(indent+" ", charTree)
Expand All @@ -269,7 +269,7 @@ def codeOutTree(indent, tree, offset):


print("")
print("")
print("")

codeOut('// Automatically generated wrapper file ')
codeOut('// Generated by scripts/build_jsfunctions.py');
Expand All @@ -287,7 +287,7 @@ def codeOutTree(indent, tree, offset):
codeOut('');
codeOut('');
codeOut('bool jswHasConstructorNamed(JsVar *parent, const char *str) {');
codeOut(' JsVar *constructorName = jsvIsObject(parent)?jsvSkipOneNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
codeOut(' JsVar *constructorName = jsvIsObject(parent)?jsvSkipOneNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR)):0;')
codeOut(' return constructorName && jsvIsName(constructorName) && jsvIsStringEqual(constructorName, str);')
codeOut('}');
codeOut('');
Expand Down Expand Up @@ -329,7 +329,7 @@ def codeOutTree(indent, tree, offset):
# codeOutTree(" ", tree[className], 0)
# codeOut(" }")
#codeOut(' // ------------------------------------------ INSTANCE METHODS WE MUST CHECK CONSTRUCTOR FOR')
#codeOut(' JsVar *constructorName = jsvIsObject(parent)?jsvSkipOneNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
#codeOut(' JsVar *constructorName = jsvIsObject(parent)?jsvSkipOneNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR)):0;')
#codeOut(' if (constructorName && jsvIsName(constructorName)) {')
#first = True
#for className in tree:
Expand Down Expand Up @@ -375,7 +375,7 @@ def codeOutTree(indent, tree, offset):
builtinChecks.append(check)


codeOut('bool jswIsBuiltInObject(const char *name) {')
codeOut('bool jswIsBuiltInObject(const char *name) {')
codeOut(' return\n'+" ||\n ".join(builtinChecks)+';')
codeOut('}')

Expand Down
8 changes: 4 additions & 4 deletions src/jsinteractive.c
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ IOEventFlags jsiGetDeviceFromClass(JsVar *class) {
JsVar *jsiGetClassNameFromDevice(IOEventFlags device) {
const char *deviceName = jshGetDeviceString(device);
if (!deviceName[0]) return 0; // could be empty string
return jsvFindChildFromString(execInfo.root, deviceName, false);
return jsvFindChildFromString(execInfo.root, deviceName);
}

NO_INLINE bool jsiEcho() {
Expand Down Expand Up @@ -595,7 +595,7 @@ NO_INLINE void jsiDumpObjectState(vcbprintf_callback user_callback, void *user_d

/** Dump the code required to initialise a serial port to this string */
void jsiDumpSerialInitialisation(vcbprintf_callback user_callback, void *user_data, const char *serialName, bool humanReadableDump) {
JsVar *serialVarName = jsvFindChildFromString(execInfo.root, serialName, false);
JsVar *serialVarName = jsvFindChildFromString(execInfo.root, serialName);
JsVar *serialVar = jsvSkipName(serialVarName);

if (serialVar) {
Expand Down Expand Up @@ -2446,7 +2446,7 @@ void jsiDumpState(vcbprintf_callback user_callback, void *user_data) {
while (jsvObjectIteratorHasValue(&it)) {
JsVar *timer = jsvObjectIteratorGetValue(&it);
JsVar *timerNumber = jsvObjectIteratorGetKey(&it);
JsVar *timerCallback = jsvSkipOneNameAndUnLock(jsvFindChildFromString(timer, "callback", false));
JsVar *timerCallback = jsvSkipOneNameAndUnLock(jsvFindChildFromString(timer, "callback"));
JsVar *timerInterval = jsvObjectGetChildIfExists(timer, "interval");
user_callback(timerInterval ? "setInterval(" : "setTimeout(", user_data);
jsiDumpJSON(user_callback, user_data, timerCallback, 0);
Expand All @@ -2463,7 +2463,7 @@ void jsiDumpState(vcbprintf_callback user_callback, void *user_data) {
jsvUnLock(watchArrayPtr);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *watch = jsvObjectIteratorGetValue(&it);
JsVar *watchCallback = jsvSkipOneNameAndUnLock(jsvFindChildFromString(watch, "callback", false));
JsVar *watchCallback = jsvSkipOneNameAndUnLock(jsvFindChildFromString(watch, "callback"));
bool watchRecur = jsvGetBoolAndUnLock(jsvObjectGetChildIfExists(watch, "recur"));
int watchEdge = (int)jsvGetIntegerAndUnLock(jsvObjectGetChildIfExists(watch, "edge"));
JsVar *watchPin = jsvObjectGetChildIfExists(watch, "pin");
Expand Down
2 changes: 1 addition & 1 deletion src/jsjit.c
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ NO_INLINE JsVar *_jsxMathsOpSkipNamesAndUnLock(JsVar *a, JsVar *b, int op) {
// Add a variable to the current scope (eg VAR statement), and return it
NO_INLINE JsVar *_jsxAddVar(const char *name) {
JsVar *scope = jspeiGetTopScope();
JsVar *a = jsvFindChildFromString(scope, name, true);
JsVar *a = jsvFindOrAddChildFromString(scope, name);
jsvUnLock(scope);
return a;
}
Expand Down
Loading

0 comments on commit f6894cd

Please sign in to comment.