Skip to content

Instantly share code, notes, and snippets.

# Perl example of static and dynamic scopes
$x = 10;
sub print_x {
print $x;
}
sub static {
my $x = 20; # doesn't affect
/**
* JavaScript static scope example.
*/
const x = 10;
function print_x() {
console.log(x);
}
extern crate syntax;
use syntax::Parser;
fn main() {
let mut parser = Parser::new();
let result = parser.parse("2 + 2 * 2");
println!("{:?}", result); // 6
}
/**
* Calculator grammar to generate parser in Rust.
*/
%lex
%%
// -----------------------------------------------
// Lexical grammar.
<!DOCTYPE html>
<html>
<head>
<title>Wasm</title>
</head>
<body>
<script>
(async () => {
/**
@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

use std::fmt::Debug;
use std::any::Any;
// Logger function for any type that implements Debug.
fn log<T: Any + Debug>(value: &T) {
let value_any = value as &Any;
// try to convert our value to a String. If successful, we want to
// output the String's length as well as its value. If not, it's a
// different type: just print it out unadorned.
macro_rules! map(
{ $($key:expr => $value:expr),+ } => {
{
let mut m = ::std::collections::HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
macro_rules! zoom_and_enhance {
(struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
struct $name {
$($fname : $ftype),*
}
impl $name {
fn field_names() -> &'static [&'static str] {
static NAMES: &'static [&'static str] = &[$(stringify!($fname)),*];
NAMES
@DmitrySoshnikov
DmitrySoshnikov / stack-params.c
Last active May 23, 2017 18:22
stack-params.c
// https://godbolt.org/g/2xOK3B
int foo(int x) {
int y = 20;
return x + y;
}
int main() {
foo(10);
return 0;