《Python源码剖析》笔记 SmallPython

本文介绍了一个简单的自制Python解释器实现,包括整数、字符串及字典等基础类型的处理,并通过命令行进行交互式输入和执行。

书中的代码没有给完整,而且有一些bug,可能是版本的不同,我的编译环境是VS2010。
文件目录:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
SmallPython.cpp的代码:

// SmallPython.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"

#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>

using namespace std;

/***********************************PyObject**********************************/
#define PyObject_HEAD \
	int refCount; \
	struct tagPyTypeObject *type

#define PyObject_HEAD_INIT(typePtr)\
	0, typePtr

typedef struct tagPyObject
{
   
   
	PyObject_HEAD;
}PyObject;
/***********************************PyObject**********************************/

/***********************************PyTypeObject**********************************/
typedef void (*PrintFun)(PyObject* object);
typedef PyObject* (*AddFun)(PyObject* left, PyObject* right);
typedef long (*HashFun)(PyObject* object);

typedef struct tagPyTypeObject
{
   
   
	PyObject_HEAD;
	char* name;
	PrintFun print;
	AddFun add;
	HashFun hash;
}PyTypeObject;

PyTypeObject PyType_Type = 
{
   
   
	PyObject_HEAD_INIT(&PyType_Type),
	"type"
};
/***********************************PyTypeObject**********************************/


/***********************************PyIntObject**********************************/
static void int_print(PyObject* object);
static PyObject* int_add(PyObject* left, PyObject* right);
static long int_hash(PyObject* object);

PyTypeObject PyInt_Type = 
{
   
   
	PyObject_HEAD_INIT(&PyType_Type),
	"int",
	int_print,
	int_add,
	int_hash
};

typedef struct tagPyIntObject
{
   
   
	PyObject_HEAD;
	int value;
}PyIntObject;

PyObject* PyInt_Create(int value)
{
   
   
	PyIntObject* object = new PyIntObject;
	object->refCount = 1;
	object->type = &PyInt_Type;
	object->value = value;
	return (PyObject*)object;
}

static void int_print(PyObject* object)
{
   
   
	PyIntObject* intObject = (PyIntObject*)object;
	printf("%d\n", intObject->value);
}

static PyObject* int_add(PyObject* left, PyObject* right)
{
   
   
	PyIntObject* leftInt = (PyIntObject*)left;
	PyIntObject* rightInt = (PyIntObject*)right;
	
	PyIntObject* result = (PyIntObject*)PyInt_Create(0);
	if(result == NULL)
	{
   
   
		printf("We have no enough memory!!"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值