Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
DmitrySoshnikov / rust-dynamic-lazy-static.md
Last active January 22, 2022 05:29
Rust notes: dynamic and global static objects

Rust notes: dynamic and global static objects

Level: novices, n00bs

Rust is a statically typed language, which helps preventing runtime bugs, and ensures memory safety at compile time, that is with no runtime costs. However, sometimes one may need using dynamic values. Also, Rust doesn't support "out of the box" complex static structures, which still can be solved with some lazy initialization tricks.

Below are some notes on dynamic data types, and global static objects in Rust programming language.

Dynamic objects

<!DOCTYPE html>
<html>
<head>
<title>Wasm</title>
</head>
<body>
<script>
(async () => {
/**
/**
* Calculator grammar to generate parser in Rust.
*/
%lex
%%
// -----------------------------------------------
// Lexical grammar.
extern crate syntax;
use syntax::Parser;
fn main() {
let mut parser = Parser::new();
let result = parser.parse("2 + 2 * 2");
println!("{:?}", result); // 6
}
/**
* JavaScript static scope example.
*/
const x = 10;
function print_x() {
console.log(x);
}
# Perl example of static and dynamic scopes
$x = 10;
sub print_x {
print $x;
}
sub static {
my $x = 20; # doesn't affect
/**
* JavaScript dynamic `this` value.
*/
function produce() {
console.log(this.x);
}
const alpha = {produce, x: 1};
const beta = {produce, x: 2};
/**
* JavaScript runtime-augmented scope example.
*/
let x = 10;
let o = {x: 30};
let storage = {};
(function foo(flag) {

JNI Example (Mac OS)

JNI (Java Native Interface) allows implementing methods in C/C++, and use them in Java.

1. Create JNIExample.java file

class JNIExample {

  // Native method, no body.
/**
* NFA (Non-deterministic finite automata)
*
* A formalism for regular grammars (to recognize strings based on regular
* expressions).
*
* Regexp parser to transform AST to NFA:
* https://www.npmjs.com/package/regexp-tree
*
* NFA/DFA fragment examples: